0

I got an array from json and I need to put each item in a <li> on my html

something like this :

names : {john, paul, ringo,george}
into <li>john</li>..

my code:

<div id="demo"></div>

script:

function onLocationsReceived(data) {
  console.log("recievd");

  for (var i = 0; i < data[0].Sensors.length; i++) {
    var sensorNames = data[0].Sensors[i].Name;
    document.getElementById("demo").innerHTML = sensorNames;
    console.log(sensorNames);
  }
}

on the concole.log it prints just fine..

document.getElementById("demo").innerHTML = '<li>' + sensorNames '</li>

something like that???

3
  • 2
    As per your code you are overwriting the text in your inner html Commented Apr 6, 2016 at 10:56
  • Possible duplicate of Printing each value of an array on a separate line Javascript Commented Apr 6, 2016 at 10:56
  • I suggest to create temporary string variable for <li> elements, and then after building it - to write it as .innerHTML. Instead of doing +=. It's better for performance and easily to maintain Commented Apr 6, 2016 at 11:00

3 Answers 3

1

Using something like below

function onLocationsReceived(data){
var html="";
  for (var i = 0; i < data[0].Sensors.length; i++) {
   var sensorNames = data[0].Sensors[i].Name;
    html+="<li>"+sensorNames+"</li>";
    console.log(sensorNames);
}
document.getElementById("demo").innerHTML=html;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Can someone please edit my answer not able to do that
1

You can use syntax below

document.getElementById('demo').innerHTML ='<li>' + sensorNames + '</li>'

1 Comment

See my previous comment about the += and put the: you can use below syntax inside a comment line - to make it more copy pastable
0

You should cache the iterative sensorNames into a var with the li and then replace the innerHTML:

var content = "",
    sensorNames;

for (var i = 0; i < data[0].Sensors.length; i++) {
    sensorNames = data[0].Sensors[i].Name;
    content += "<li>" + sensorNames + "</li>";
}

document.getElementById("demo").innerHTML = content;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.