var div = document.getElementsByClassName('news-story')[0], h5 = div.getElementsByTagName('h5'), p = div.getElementsByTagName('p'), data = JSON.parse( my_JSON_data ); data.items.forEach(function(v,i) { h5[i].innerHTML = v.title; p[i].innerHTML = "By: " + v.author; });
JSFIDDLE DEMO
If you need to support older browsers, you can use the typical for statement instead of the forEach method.
for( var i = 0; i < data.items.length; ++i ) { var v = data.items[i]; h5[i].innerHTML = v.title; p[i].innerHTML = "By: " + v.author; }
And I would suggest using the identifier instead of the class for the news-story element, so you can use getElementById instead (if, of course, you have several).
If this is not possible, you can use the compatibility function from MDN for getElementsByClassName .
If you need to create internal elements, then here is one way:
var div = document.getElementsByClassName('news-story')[0], data = JSON.parse( my_JSON_data ), html; html = data.items.map(function(v,i) { return '<h5>' + v.title + '</h5>' + '<p>By: ' + v.author + '</p>'; }).join(''); div.innerHTML = html;
JSFIDDLE DEMO
@ Xeon06 shows how his answer uses createElement() , which is arguably the best approach.
Here's how I would do it:
var div = document.getElementsByClassName('news-story')[0], frag = document.createDocumentFragment(), data = JSON.parse( my_JSON_data ); data.items.forEach(function(v,i) { frag.appendChild( document.createElement('h5') ).innerHTML = v.title; frag.appendChild( document.createElement('p') ).innerHTML = "By: " + v.author; }); div.appendChild( frag );
JSFIDDLE DEMO
And of course, you can change it to use the for statement:
var div = document.getElementsByClassName('news-story')[0], frag = document.createDocumentFragment(), data = JSON.parse( my_JSON_data ); for( var i = 0; i < data.items.length; ++i ) { var v = data.items[i]; frag.appendChild( document.createElement('h5') ).innerHTML = v.title; frag.appendChild( document.createElement('p') ).innerHTML = "By: " + v.author; } div.appendChild( frag );
The advantage of using documentFragment is that you can make one addition to the DOM through a fragment instead of several additions. This gives better performance, especially if you have a large dataset.