How do I dynamically populate html elements with JSON Data with Javascript not jQuery?

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.

Answers


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.


Need Your Help

Setting a variable

sql

Well I have a few questions and I like to make sure I am understanding what I am doing. So here it is I am working on a project and I am suppose to Create a variable called MinOrder and populate it...

Get an array from a formula

ios nsmutablearray nsarray

I am building an ios ipad app and I have the following formula in the code to calculate a Lump Sum amount:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.