I have a JSON object:
var txt = '{"employees":[' +
'{"firstName":"John","lastName":"Doe","time":"9:15am","email":"[email protected]" },' +
'{"firstName":"Anna","lastName":"Smith","time":"9:15am","email":"[email protected]" },' +
'{"firstName":"Peter","lastName":"Jones" ,"time":"9:15am","email":"[email protected]"}]}';
That I want to print as a list in between div statements:
- John Doe
- 9:15am
Anna Smith
- 9:15am
Peter Jones
- 9:15am
- [email protected]
The HTML that I'm trying to populate looks like this:
<div class="info">
<ul>
<li id="name"></li>
<li id="time"></li>
<li id="email"></li>
</ul>
</div>
How do I accomplish this?
<!DOCTYPE html>
<html>
<body>
<h2>Create Object from JSON String</h2>
<div id="output">
</div>
<script type="text/javascript">
var txt = '{"employees":[' +
'{"firstName":"John","lastName":"Doe","time":"9:15am","email":"[email protected]" },' +
'{"firstName":"Anna","lastName":"Smith","time":"9:15am","email":"[email protected]" },' +
'{"firstName":"Peter","lastName":"Jones" ,"time":"9:15am","email":"[email protected]"}]}';
var employees=JSON.parse(txt).employees;
var container=document.getElementById("output");
for (i=0;i<employees.length;i++) { //Loops for the length of the list
var info=document.createElement('div');
info.className='info'; //Creates a new <div> element and adds the class info to it
var ul=document.createElement('div'); //Creates <ul> element
info.appendChild(ul); //Adds the <ul> to the newly created <div>
var name=document.createElement('li');
name.className='name'; //Should use class, not id, as ID must be unique
name.innerHTML=employees[i].firstName+' '+employees[i].lastName; //Adds name
ul.appendChild(name);
var time=document.createElement('li');
time.className='time';
time.innerHTML=employees[i].time;
ul.appendChild(time);
var email=document.createElement('li');
email.className='email';
email.innerHTML=employees[i].email;
ul.appendChild(email);
container.appendChild(info); //Adds the final generated HTML to the page
} //Will repeat for each item in list.
</script>
</body>
</html>
classand notidto identify name, time and email as you will end up with multiple instances of them.