Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Aug 2011
    Thanked 0 Times in 0 Posts

    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:

    { "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>


    Thank you

  2. #2
    New to the CF scene
    Join Date
    May 2011
    Thanked 0 Times in 0 Posts
    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:

    //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


Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts