www.webdeveloper.com
Results 1 to 3 of 3

Thread: Json

  1. #1
    Join Date
    Nov 2010
    Posts
    1

    Question Json

    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>

  2. #2
    Join Date
    Apr 2003
    Location
    Netherlands
    Posts
    21,654
    Code:
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title></title>
    
    <script type="text/javascript">
    window.onload=function() {
    var classList=[];
    if(document.getElementsByClassName) {
        classList = document.getElementsByClassName('news-story');
        }
    else {
        var aObj=document.getElementsByTagName('*');
        var i=aObj.length; 
        while(i--) { 
            if(aObj[i].className.indexOf('news-story')!=-1) {classList.push(aObj[i]);}
            }
        }
    for(var i=0; i<classList.length; i++) {
        var text = '';
        for (x in JSON.items){
            text += '<h5>'+JSON.items[x].title+'</h5><p>By: '+JSON.items[x].author+'</p>';
            }
        classList[i].innerHTML = text;
        }
    };
    
    JSON = {
        items: [
            { "title": "sample 1", "author": "author 1" },
            { "title": "sample 2", "author": "author 2" }
            ]
        };
    </script>
    
    <style type="text/css">
    * {margin:0;padding:0;}
    .news-story {border:1px solid;margin:1em;}
    </style>
    
    </head>
    <body>
    <div class="news-story"></div>
    <div class="news-story"></div>
    </body>
    </html>

  3. #3
    Join Date
    Jul 2006
    Location
    Maryland
    Posts
    2

    Thanks a bunch!

    What are the best resources to learn this language?

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

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
  •  
HTML5 Development Center



Recent Articles