Print JavaScript dictionary into div - javascript

I have a JavaScript map that looks like this
var code = {'as':'','db':'','id3':'','term':''};
And want to print for example as into a div. If I do this, I get 'Undefined' inside the div. As I understand, this means the value itself is undefined. How can I "predefine" the empty string?
Update:
As there seems to be a lot of confusion: If I put code[1] into a div using the code above, the div contains 'Undefined'.
Update:
The markup looks as follows
<div id="cont" class="diff">
<div id="editor">
<div id="funcRow">
<ul>
<li><a onclick="changeTab(0)">Settings</a></li>
<li><a onclick="changeTab(1)">Knowledge</a></li>
<li><a onclick="changeTab(2)">Layer 4</a></li>
<li><a onclick="changeTab(3)">Hardware</a></li>
</ul>
</div>
<div id="text" contenteditable=true>
</div>
</div>
</div>
and changeTab(i) looks as follows:
function changeTab(i) {
code[activeTab] = document.getElementById("text").innerHTML;
document.getElementById("text").innerHTML = code[i];
document.getElementsByTagName("ul")[0].getElementsByTagName("li")[i].getElementsByTagName("a")[0].className="active";
document.getElementsByTagName("ul")[0].getElementsByTagName("li")[activeTab].getElementsByTagName("a")[0].className="";
activeTab = i;
}

The code below should be self-explanatory, just stringify before outputting
var div = document.getElementById('test');
var code = {'as':'','db':'','id3':'','term':''};
div.innerHTML = '<pre>' + JSON.stringify(code, null, 4) + '</pre>';
<div id="test"></div>
If you just want to output one of the values, use the key to access it
var div = document.getElementById('test');
var code = {'as':'1','db':'2','id3':'3','term':'4'};
div.innerHTML = code.as; // dot notation, or "code['as']" for bracket notation
<div id="test"></div>

Try using for..in loop, .innerHTML ; using break to stop loop after as property printed to div
// "predefine" empty strings with `1` , `2, `3`, `4`
var code = {'as':'1','db':'2','id3':'3','term':'4'};
var div = document.querySelector("div");
for (var prop in code) {
if (prop === "as") {
div.innerHTML += code[prop];
break;
}
}
<div></div>

The problem was me trying to call code[i], which is not possible in JavaScript. Undefined popped up because JS tried to evaluate the value to the key, which was not present at first.

Like this, but since the value is "nothing", the output is "nothing".
var div = document.getElementById('test');
var code = {'as':'','db':'','id3':'','term':''};
// code['as'] = "hello, world"; // un-comment to see something
div.innerHTML = '[' + code['as'] + ']';
<div id="test"></div>
Here is a second idea, based on the revision of your question:
var div = document.getElementById('test');
var keys = ['as', 'db', 'id3', 'term' ];
var code = {};
for (var i = 0; i < keys.length; ++i) code[keys[i]] = '';
code['as'] = "hello, world";
// code[keys[0]] = "hello, world"; // or this
div.innerHTML = '[' + code['as'] + ']' + ' (' + code[keys[0]] + ')';
<div id="test">X</div>

Related

Use Javascript to write names that don't appear in master list to div with id

Working demo at http://verlager.com/pairing.php uses document.write() but I would prefer to write to a div's ID. I have tried several methods but I can't get the for loop to write to div with id of "textDiv".
<script>
function newly_minted() {
var res = "Attaya, James J|Blazak, Stephen A|Cavanaugh, Michael P|Decker, Howard|";
document.getElementById("textDiv").textContent = res;
}
newly_minted();
</script>
<div id="textDiv" style="background:green; color:fff; display:table; height:10rem; width:40rem; margin:4rem auto; clear:both;"></div>
For original post:
This code replaces textDiv content because of the simple assignment used:
var div = document.getElementById("textDiv");
div.textContent = resort;
var text = div.textContent; //should append not replace!
Try the '+=' operator instead:
var div = document.getElementById("textDiv");
div.textContent += resort;
var text = div.textContent; //should append not replace!
For the updated post:
Declare newly_minted before calling it from a different script element. Hoisting function declarations only applies to the script element in which the function is declared.
Replace $( resort) with resort (and split resort on "|" as in the original). The trailing "|" is not altered in this demonstration:
function newly_minted() {
var res = "Attaya, James J|Blazak, Stephen A|Cavanaugh, Michael P|Decker, Howard|".split('|');
for (let i = 0; i < res.length; i++) {
var resort = res[i] + " ● ";
$( "#textDiv" ).append(resort);
}}
newly_minted();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="textDiv"></div>
Alternatively, without using jQuery, preparing text content first and removing trailing dots:
function newly_minted() {
var res = "Attaya, James J|Blazak, Stephen A|Cavanaugh, Michael P|Decker, Howard|".split('|');
for (var i = 0, text =""; i < res.length; i++) {
text += res[i] + " \u25cf ";
}
text = text.replace(" \u25cf \u25cf ", ""); // remove two trailing dots
document.getElementById("textDiv").textContent = text;
}
newly_minted();
<div id="textDiv"></div>

Modify innerHTML of a child div

I am new to JavaScript. What I am trying to do is make a div and inside of it there will be another div. Within my script code I am trying to create new instances of that div using factory function if that is the right name for it, and then change the innerHTML of the child div if that is possible. Thanks in advance.
<div class = "loopBlock" style="width:350px;">
<fieldset>
<legend style="color:black;font-weight:bold;">While Loop</legend>
<table>
<tr>
<td>Condition:</td>
<td><input type="text" /></td>
</tr>
</table>
<div class = "codeDivClass" id = "codeDiv">
HelloWorld!
</div>
</fieldset>
</div>
<script>
var loopDiv = document.getElementsByClassName("loopBlock");
var loopi =1;
function loopObject(){
var loopDivObject = document.createElement("div");
loopDivObject.innerHTML = loopDiv[0].innerHTML;
loopDivObject.className = "loopBlock";
loopDivObject.id = "loopBlock"+loopi;
loopi++;
return loopDivObject;
};
var functionCodeDiv = document.getElementById("codeDiv");
for (i=0; i<5; i++){
var tempLoop = loopObject();
functionCodeDiv.appendChild(tempLoop);
var id = "loopBlock"+i+1;
document.getElementById(id).getElementsByTagName('div')[0].innerHTML = "bye";
}
</script>
Didn't really get how it should work, but I'm sure I've found a mistake.
var id = "loopBlock"+i+1;
you have to replace with:
var id = "loopBlock"+(i+1);
Example i is 2.
In first case you get: "loopBlock21"
In second (my) case, you'll get "loopBlock3"
The problem is in operator precedence. Since in this line
var id = "loopBlock" + i + 1;
you have two + (unary plus) operators with the same precedence they will act as a string concatenation operators, because one of the operands is a string ("loopBlock").
In your case you want to group i + 1 with parentheses to make the expression evaluate first as arithmetic addition operator. After that string concatenation with "loopBlock" will produce expected result:
var id = "loopBlock" + (i + 1);
Demo: http://jsfiddle.net/0091n9tt/
I think you're problem in is this line:
document.getElementById(id).getElementsByTagName('div')[0].innerHTML = "bye";
What you are actually doing is trying to gett divs inside the newly created div (loopBlock), which is empty.
You already have a reference to the block you want to modify the innerHTML; you can simply use it like this:
tempLoop.innerHTML = "bye";
So you're for loop would look like this:
for (i=0; i<5; i++){
var tempLoop = loopObject();
functionCodeDiv.appendChild(tempLoop);
tempLoop.innerHTML = "bye";
}
Note that you don't need the id anymore.

How to get text of div by id in variable

I have a string variable called the res.
Within this variable there is HTML code.
Each Div in variable within the has a id.
var res = "<div id="1">1</div>
<div id="2">12</div>
<div id="3">123</div>
<div id="4">1234</div>";
var content-div-1 = ??;
var content-div-2 = ??;
var content-div-3 = ??;
var content-div-4 = ??;
I would like to give the id of div and give me values of inside Div.
The question has been answered, but there's an alternative without jQuery
var res = '<div id="1">1</div>'+
'<div id="2">12</div>'+
'<div id="3">123</div>'+
'<div id="4">1234</div>';
function findMe(txt, id){
var matches = txt.match(new RegExp('<div\\s+id="'+id+'">[\\S\\s]*?<\\/div>'), 'gi');
if(matches) return matches[0].replace(/(<\/?[^>]+>)/gi, '');
return '';
}
var content1 = findMe(res,1);
var content2 = findMe(res,2);
var content3 = findMe(res,3);
var content4 = findMe(res,4);
JSFiddle
As you've tagged your question jquery, I assume this is in a browser context (or some other context with a DOM). If so, the simplest way to is to parse the HTML and use the resulting disconnected DOM tree:
var res = '<div id="1">1</div>' +
'<div id="2">12</div>' +
'<div id="3">123</div>' +
'<div id="4">1234</div>';
var parsed = $(res);
var contentDiv1 = parsed.filter("[id=1]").text(); // See note below
snippet.log("1: " + contentDiv1);
var contentDiv2 = parsed.filter("[id=2]").text(); // See note below
snippet.log("2: " + contentDiv2);
// ...and so on (or use a loop)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Note: Although id value starting with digits are valid HTML, it's awkward to use them because in a CSS id selector (#foo), you can't start the ID value with an unescaped digit (e.g., #1 is an invalid selector). That's why I've had to use the attribute selector [id=1] above. You can work around it with escaping, but by far the best option is just to not start ID values with digits in the first place.

Output html tag as text into a div, each array element on separate line

I have an array in javascript file called newElements.
The format likes this:
newElements: Array[3]
0: "<p class='Day'>asdasd</p>"
1: "<p class='Day'>123123</p>"
2: "<p class='Day'>Test</p>"
length: 3
And I have a div.panel-body.
What I did is
for( var i = 0; i < newElements.length; i++) {
new_content += newElements[i];
}
$(".panel-body").text(new_content);
It gives me output looks like this:
However, I want the div format like this:
<p class="Day">Some Text</p>
<p class="Day">Another Text</p>
<p class="Session">TEXT</p>
Each html tag on a separate line.
Yes, I know the <br> tag, but the question is, if I add <br> , the <br> tag will be treated as plain text, the output will become like this: <p class="Day">asdasd</p><br><p class="Day">asds</p>
So, could someone give me a nice way to show the output to screen the way I want it. You already have the array I give you.
And if I use html() function, the <p> will be treated as real html tag, that's not what I want, I want they be shown.
If you don't want to display the code, instead of .text(), use .html().
Fiddle: http://jsfiddle.net/q4AeR/
My mistake. Since you DO want to show the actual code, add each to its own new element, within the loop. This is the best I can think of:
Fiddle: http://jsfiddle.net/Hb9mC/
Try
for( var i = 0; i < newElements.length; i++) {
$(".panel-body").append(document.createTextNode(newElements[i])).append('<br/>');
}
http://jsfiddle.net/9z3zE/1/
I assume you want to display your code including line breaks. Convert your HTML to entities and add line breaks:
function htmlEntities(str) {
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
}
var newElements = ['<p class="Day">asdasd</p>,<p class="Day">123123</p>,<p class="Day">Test</p>'],
output = '';
for(var i = 0; i < newElements.length; i++) {
output += htmlEntities(newElements[i]) + '<br />';
}
$('.panel-body').html(output);
http://jsbin.com/mefuhufo/1/edit
<div class="hello">
</div>
<script>
var mycars = new Array();
mycars[0] = "<p class='Day'>Hello Xinrui Ma</p>";
mycars[1] = "<p class='Day'>this is the array</p>";
mycars[2] = "<p class='Day'>hopes it fits your need</p>";
var divHello = $('div.hello')
$.each(mycars, function( index, value ) {
divHello.append(value);
});
</script>

How to write all data from Array?

I have HTML like :
<div id="divid">
1
2
3
.....................
</div>
I have script to get all links from a div like :
<script>
var links = document.getElementById('divid').getElementsByTagName('a') ;
</script>
Then I want write link into class like :
<script>
var links = document.getElementById('divid').getElementsByTagName('a') ;
document.write("<div class="'+link[1]+" "+ link[i]+'">Class is added links</div>");
</script>
That mean after write I have HTML:
<div class="d#link1 d#link2 d#link3">Classes is added links</div>
How can I do this? Using for loop or not? how?
You have to get the href property from each element. Put them in an array, and you can just join the strings:
var elements = document.getElementById('divid').getElementsByTagName('a');
var links = [];
for (var i = 0; i < elements.length; i++) {
links.push(elements[i].href);
}
document.write("<div class="' + links.join(" ") + '">Class is added links</div>");
Use join in combination with map:
var classString = links.map(function(link) { return link.attributes.href; } ).join(' ');

Categories