Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
67
rated 0 times [  73] [ 6]  / answers: 1 / hits: 68739  / 13 Years ago, tue, november 29, 2011, 12:00:00

I have this following JSON data snippit:



{items: [
{
title: sample 1,
author: author 1
},
{
title: sample 2,
author: author 2
}
]}


How do I populate the following html elements with this data:



<div class=news-story>
<h5>sample 1</h5>
<p>By: author 1</p>
<h5>sample 2</h5>
<p>By: author 2</p>
</div>


I want accomplish this with Javascript not jQuery.


More From » html

 Answers
286

Loop through them and use the DOM functions:



var news = document.getElementsByClassName(news-story)[0];
var items = json.items;
for(var i = 0; i < items.length; i++) {
var h5 = document.createElement(h5);
h5.innerHTML = items[i].title;
news.appendChild(h5);
var p = document.createElement(p);
p.innerHTML = items[i].author;
news.appendChild(p);

}


http://jsfiddle.net/AWRAW/



getElementsByClassName will not work in versions of IE prior to 9. If you need to support those though, you're really better off using jQuery.


[#88846] Monday, November 28, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cartersinceren

Total Points: 442
Total Questions: 116
Total Answers: 106

Location: San Marino
Member since Thu, Jun 30, 2022
2 Years ago
;