textContent object property doesn't work - javascript

var container = document.getElementById("grid-container");
var btn = document.getElementById("btn");
var div;
var reuqest;
function HTTPRequest(url) {
request = new XMLHttpRequest();
request.open('GET', url);
request.onload = function() {
result(request);
};
request.send();
}
function result(data){
var res = JSON.parse(data.responseText);
var array = res.results;
var myObj = array[0];
console.log(myObj);
for (var i = 0; i < Object.keys(myObj).length; i++) {
div = document.createElement("div");
div.className = "grid-item";
container.appendChild(div);
for (let key in myObj) {
console.log(myObj[key]);
div.textContent = myObj[key];
}
}
}
btn.addEventListener('click', function() {
HTTPRequest('https://itunes.apple.com/search?term=jack+johnson','author');
});
I am trying to loop through all properties of the object and give the divs I created the text content of each property of the object above.
For some reason I get:
true instead of "track", "song" etc...
Do you know why?
Thanks

The last key-value pair of every object from that response is:
"isStreamable":true
Therefore, when you're assigning a value to that div as follow div.textContent = myObj[key] you're losing the previously assigned values.
A recommendation is to concatenate the previous values, for example:
div.textContent += separator + myObj[key]
Where separator could be <br>, \n or whatever string you think is suitable.
This is a sample of a response from https://itunes.apple.com/search?term=jack+johnson

Update the innerHTML of div like this instead of textContent and also change = operator to +=.
var myObj = {
wrapperType: "track",
kind: "song",
artistId: 909253,
collectionId: 879273552,
trackId: 879273565
}
var div = document.getElementById("test");
var content = ""
for (let key in myObj) {
content += key + ": " + myObj[key] + "<br>";
}
div.innerHTML = content;
<div id="test">It is a test</div>
Instead of for(let ... in ...) you can use this (According to #Jonathan-Lonowski's answer)
let myObj = {
wrapperType: "track",
kind: "song",
artistId: 909253,
collectionId: 879273552,
trackId: 879273565
},
container = document.getElementById("container");
Object.entries(myObj).forEach(function(itm) {
div = document.createElement("div");
div.className = "grid-item";
container.appendChild(div);
div.textContent = itm[0] + ": " + itm[1];
});
<div id="container"></div>

If you're trying to append a div for each of myObj's keys/values, then it should be unnecessary to use two loops to iterate through the keys.
Saving the list of keys from myObj that the for loop is iterating over…
var keys = Object.keys(myObj);
for (var i = 0; i < keys.length; i++) {
// ...
}
You can get the key for each iteration using the index, i, without needing the additional for..in loop:
var key = keys[i];
div.textContent = myObj[key];
Combined:
function result(data){
var res = JSON.parse(data.responseText);
var array = res.results;
var myObj = array[0];
var keys = Object.keys(myObj);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
div = document.createElement("div");
div.className = "grid-item";
div.textContent = myObj[key];
container.appendChild(div);
}
}

You are not looping well on the object here as you use for
You better use this syntax : https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Object/keys
Object.keys(myObj).map((key) => {
console.log(myObj[key], key)
}
or
Object.keys(myObj).map(function (key) {
console.log(myObj[key], key)
}

Related

Unable to parse json using javascript

I have a json which i'm trying to parse it using javascript. Iteration count and the pages getting appended to it are going to be dynamic.
Expected Result
Just like the above image i'm able to take dynamic iteration keys from the below mentioned json.
Iteration.json
{
"count":[
{
"iteration1":[
{
"PageName":"T01_Launch"
},
{
"PageName":"T02_Login"
}
]
},
{
"iteration2":[
{
"PageName":"T01_Launch"
},
{
"PageName":"T02_Login"
}
]
}
]
}
When i click on iteration it has to populate the corresponding pagenames for that particular iteration as shown in expected result image. But what i get actually is (refer the image below):
Please find the code that i tried:
var pagenamearray = [];
$.getJSON("iteration.json", function(json) {
var hits = json.count;
var iterations, tnname, iteration;
for (var k in hits) {
var value;
if (hits.hasOwnProperty(k)) {
value = hits[k];
var iteratearray = [];
for (var j in value) {
if (value.hasOwnProperty(j)) {
j;
var check = value[j];
for (var i in check) {
if (check.hasOwnProperty(i)) {
var test = check[i];
for (var t in test) {
if (test.hasOwnProperty(t)) {
var pagename = JSON.stringify(t)
var arr = []
if (pagename.includes("PageName")) {
//alert("Key is " +pagename + ", value is" + JSON.stringify(test[t]));
for (var it = 0; it < hits.length; it++) {
if ((Object.keys(hits[it])).includes(j)) {
var pagenamevalue = test[t];
arr[it] = [];
arr.push(pagenamevalue);
}
}
}
//alert(arr)
}
pagenamearray.push(arr);
}
}
}
}
var row = document.createElement('div');
row.setAttribute("class", "row");
row.setAttribute("id", j)
var gridWidth = document.createElement('div');
gridWidth.setAttribute("class", "col-lg-12");
var panelRoot = document.createElement('div');
panelRoot.setAttribute("class", "panel panel-default");
var panelHeading = document.createElement('div');
panelHeading.setAttribute("class", "panel-heading");
var heading3 = document.createElement('a');
heading3.setAttribute("class", "panel-title");
var icon = document.createElement('i');
icon.setAttribute("class", "fa fa-long-arrow-right fa-fw");
heading3.appendChild(icon);
heading3.innerHTML = j;
heading3.setAttribute("onclick", "doit('" + j + "');");
panelHeading.appendChild(heading3);
/* var panelBody=document.createElement('div');
panelBody.setAttribute("class","panel-body");
panelBody.setAttribute("id","panellinks");*/
panelRoot.appendChild(panelHeading);
// panelRoot.appendChild(panelBody)
gridWidth.appendChild(panelRoot);
row.appendChild(gridWidth);
document.getElementById("analysis").appendChild(row);
}
}
}
});
function doit(value) {
var ul = document.getElementById(value);
if (ul != undefined) {
$("#" + "expandlinks").remove();
$("#" + value + value).remove();
}
var accordion = document.getElementById(value);
var panelBody = document.createElement('div');
panelBody.setAttribute("class", "panel-body");
panelBody.setAttribute("id", "expandlinks")
var tablediv = document.createElement('div')
var tablelink = document.createElement('a');
tablediv.appendChild(tablelink);
var graphdiv = document.createElement('div')
var graphlink = document.createElement('a');
graphdiv.appendChild(graphlink);
var recommndiv = document.createElement('div');
var recommendlink = document.createElement('a');
recommndiv.appendChild(recommendlink)
//alert(pagenamearray.length)
tablelink.innerHTML = pagenamearray;
/*graphlink.innerHTML="Timeline View";
recommendlink.innerHTML="Recommendations";*/
panelBody.appendChild(tablediv);
panelBody.appendChild(recommndiv);
panelBody.appendChild(graphdiv);
accordion.appendChild(panelBody);
}
Any advise on how to achieve this would be of great help. Thanks in advance.
I think the problem is how you assign the pagenamearray to tablelink.innerHTML. This converts the array to a string, converting all elements in the array to a string too and separating them by a comma each. However, your pagenamearray contains some empty arrays too; these will convert to an empty string in the process, but will still have a comma before and after them.
In your example code above, the pagenamearray will end up with a value of [[[],"T01_Launch"],[[],"T02_Login"],[null,[],"T01_Launch"],[null,[],"T02_Login"]] - when converted to a String, this will result in ",T01_Launch,,T02_Login,,,T01_Launch,,,T02_Login". So instead of assigning it to the innerHTML value directly, you'll first have to filter out the empty arrays and null values.

document.getElementById class applies to the whole array instead of each element

<p><span id="sr" class="btn">elements of the array</span></p>
for(var i = 0; i < myarray.length; i++)
{
var sr = (function(val) {
btn = document.createElement('button');
btn.data = val;
btn.innerHTML = val;
btn.addEventListener('click', checkAnswer);
document.body.appendChild(btn);
return btn.data = val;
})//(myarray[i]);
document.getElementById("sr").innerHTML = myarray;
}
With this code the elements of the array appear in the html span. I want each element to appear as a button, as defined in the class "btn". However, the class changes the style of the array as a whole, not as single buttons. What is the correct way to define the style of each button?
I tried document.getElementById("sr").innerHTML = myarray.class="btn";. It does not work. Definitely not the correct syntax. Any idea?
Is this what you want to achieve?
let container = document.getElementById('sr');
let array = ['element1', 'element2', 'element3'];
function checkAnswer () {
console.log('Selected answer: ', this.textContent);
}
for (let i = 0; i < array.length; i++) {
let button = document.createElement('button');
button.textContent = array[i];
button.addEventListener('click', checkAnswer);
container.appendChild(button);
}
<p><span id="sr" class="btn"></span></p>
If I understand you correctly, you want to add btn class to your dynamically created buttons with myarray elements.
What is the correct way to define the style of each button?
I tried document.getElementById("sr").innerHTML = myarray.class="btn";
You can use element.classList.add('your-class');
var myarray = ["Array", "elements"]; //let's say
for (var i = 0; i < myarray.length; i++) {
var sr = (function(val) {
btn = document.createElement('button');
btn.data = val;
btn.innerHTML = val;
btn.classList.add("btn")
btn.addEventListener('click', checkAnswer);
document.body.appendChild(btn);
return btn.data = val;
})(myarray[i]);
//document.getElementById("sr").innerHTML = myarray;//I don't know why this line here?
}
function checkAnswer(e){
}
Use Element.dataset instead of creating a .data property. Pass i to IIFE. If you are trying to display the array myarray as .innerHTML of #sr, concatenate "[" to beginning and "]" to end of myarray setting at .innerHTML, as .innerHTML casts Array to String.
If you are trying to append created element to #sr, do not append element to document.body, but #sr.
function checkAnswer() {
console.log(this.dataset.value)
}
var myarray = [1, 2, 3];
for (var i = 0; i < myarray.length; i++) {
(function(val) {
var btn = document.createElement('button');
btn.dataset.value = val;
btn.className = "btn"; // set `btn` `.className` to `"btn"`
btn.innerHTML = val;
btn.addEventListener('click', checkAnswer);
document.body.appendChild(btn);
// document.getElementById("sr").appendChild(btn);
})(i);
}
document.getElementById("sr").innerHTML = "[" + myarray + "]";
<p><span id="sr" class="btn">elements of the array</span></p>

mapping Json data and adding data attr

I have a difficulty with mapping my my Json data. I would like to add data attr to each div with .name class. So as the result is like that:
<div class="name" data-key="sth"> sty</div>
Key can be got like that: ['streme'].key
here is my buggy JS:
function getExistingLinks() {
$.post( "http://0.0.0.0:9292/api/links", function( data ) {
var names = data.map(function (i) {
return i['link'].name
});
var keys = data.map(function (i) {
return i['link'].key
});
var container = document.querySelector(".link-names");
names.forEach(function(name) {
var div = document.createElement('div');
div.innerHTML = name;
$('div').addClass("name");
// $('div').each( function(index) {
$('div')[index].data("key") = keys[index];
}
container.appendChild(div);
});
});
return false;
}
names.forEach(function(name,index) {
var div = document.createElement('div');
div.innerHTML = name;
$(div).addClass("name");
$(div).data("key") = keys[index];
});
You need to remove the quotes in the $() selector!
As per your comment, may be try doing like:
var i = 0;
names.forEach(function(name) {
var div = document.createElement('div');
div.innerHTML = name;
$('div').addClass("name");
$('div').data("key", keys[i]);
container.appendChild(div);
i++;
});
the preferred method is to only add to the DOM once, as adding to the DOM will cause a redraw on each.
psuedo code as not sure what name represents in your innerHTML:
var divs = [];
for (var i, len = names.length; i < len; i++) {
divs.push($(''+name+'').data("key", keys[i]));
}
$container.append(divs);
http://codepen.io/jsdev/pen/2866265243563efd79cf05a5b12202b3
try something like this
$('.name').data('key') //will give you sth

Building dynamic links in Javascript

I have this code below:
for (var index in mv.exifImages) {
var p = document.createElement("p");
var oText = document.createTextNode("link" + index);
p.appendChild(oText);
var info = mv.exifImages[index];
p.onclick = function() {
mv.openNewWindow(info);
};
ele.appendChild(p);
}
I want to create paragraph elements and when I click on them open a new window with correct array content. But I am anable to biuld different links. All my paragraphs open a new window with the array contents at the last index. Is there a trick around this?
I think this should work:
for (var index in mv.exifImages) {
var p = document.createElement("p");
var oText = document.createTextNode("link" + index);
p.setAttribute("indexAttr",index);
p.appendChild(oText);
p.onclick = function() {
mv.openNewWindow(mv.exifImages[this.getAttribute("indexAttr")]);
};
ele.appendChild(p);
}
The following works...
for (var index in mv.exifImages) {
var p = document.createElement("p");
var oText = document.createTextNode("link" + index);
p.appendChild(oText);
var info = mv.exifImages[index];
p.onclick = openNew(info);
ele.appendChild(p);
}
function openNew(a) {
return function() {
mv.openNewWindow(a);
}
}

Get the list of attributes of a HTML string using Javascript

How can I get the list of attributes of an HTML string using Javascript? Here's my code so far.
function traverse_test(){
var root=document.getElementById('arbre0').childNodes;
for(var i=0;i<root.length;i++){
var lis = root[i];
if (lis =='[object HTMLUListElement]') {
for (var member in lis) {
if (typeof lis[member] == "string") {
var assertion = lis[member];
var resultat = assertion.search(/..Bookmarks/);
if (resultat != -1) {
output.innerHTML+= lis[member];
// Here I'd like to have the list of lis[member] attributes
for(var attr in lis[member].attributes) {
output.innerHTML+=lis[member].attributes[attr].name + "=\""+ lis[member].attributes[attr].value + "\"";
}
break;
}
}
}
}
}
}
Use the Node.attributes property of a DOM element. Example:
var foo = document.getElementById('foo'),
attrs = foo.attributes,
i = attrs.length,
attr;
while (i--)
{
attr = attrs[i];
console.log(attr.name + '="' + attr.value + '"');
}
Demo: http://jsfiddle.net/mattball/j8AVq/
Seems like all these answers point to how to get an attr list from a node but the question asks for attrs from an HTML string. Here is my 2cents.
//turn your string into a node and get your html strings NamedNodeMap
var temp = document.createElement("div");
temp.innerHTML = "<div attr-1 attr-2 attr-3 attr-4></div>";
temp = temp.firstElementChild.attributes;
//put the attributes in a an array
var list = Object.keys(temp).map( function( index ) { return temp[ index ] } );
console.log( list );
If you know the attributes to get the value you can do:
var MyValue = document.getElementById("myimage").getAttribute("src")
In JavaScript to loop all attributes:
var el = document.getElementById("someId");
var arr = [];
for (var i=0, attrs=el.attributes, l=attrs.length; i<l; i++){
arr.push(attrs.item(i).nodeName);
}
The above code was taken from this question
Jquery might be another option:
http://plugins.jquery.com/project/getAttributes
[].slice
.apply(document.querySelector('something').attributes)
.forEach(function(item){
console.log(item, item.name, item.value);
});

Categories

Resources