Go Back   CodingForums.com > :: Client side development > JavaScript programming > DOM and JSON scripting

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 08-01-2011, 10:13 PM   PM User | #1
Adamor
New to the CF scene

 
Join Date: Aug 2011
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
Adamor is an unknown quantity at this point
Dynamically populate data with JSON using JavaScript or Jquery

Hello All,

I'm diving into JSON for the first time and I was wondering how would I dynamically populate the following into all elements with a class name of ‘news-story’ on a page using a) jQuery and b) raw javascript:

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


-------------------------------------------


expected output:

<div class="news-story">

<h5>sample 1</h5>
<p>By: author 1</p>
<h5>sample 2</h5>
<p>By: author 2</p>

</div>


Thank you
Adamor is offline   Reply With Quote
Old 08-05-2011, 02:39 PM   PM User | #2
Zholen
New to the CF scene

 
Join Date: May 2011
Posts: 4
Thanks: 0
Thanked 0 Times in 0 Posts
Zholen is an unknown quantity at this point
Ok, well first, simply use jQuery.parseJSON('jsonString') to turn your JSON into a javascript object. Then just loop through the 'items' array in that object and create then append any new DOM elements you need setting there html as you go.. EX:

Code:
//parse JSON into object
var newsInfo = $.parseJSON(myJSONString);
//Create news-story div
var newsContainer = $('<div class="news-story"></div>');

//Loop through items and add to newsContainer
for(var i=0; i < newsStory.items.length; i++) {
   newsContainer.append('<h5>' + newsStory.items[i].title + '</h5>');
   newsContainer.append('<p>' + newsStory.items[i].author + '</p>');
}

//Add newsContainer to DOM
$('#IContainTheNews').append(newsContainer);
Zholen is offline   Reply With Quote
Reply

Bookmarks

Tags
javascript, jquery, json

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 09:47 AM.


Advertisement
Log in to turn off these ads.