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

后端 未结 7 1812
无人及你
无人及你 2020-12-24 09:46

I have this following JSON data snippit:

{\"items\": [
 {
   \"title\": \"sample 1\",
   \"author\": \"author 1\"
 },
 {
  \"title\": \"sample 2\",
  \"aut         


        
7条回答
  •  情歌与酒
    2020-12-24 10:25

    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 a 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'd suggest using an ID instead of a class for the news-story element, so you can use getElementById instead (unless of course you have several of them).

    If that's impossible, you may want to use a compatibility function from MDN for getElementsByClassName.


    If you needed to create the inner elements, then here's one way:

    var div = document.getElementsByClassName('news-story')[0],
        data = JSON.parse( my_JSON_data ),
        html;
    
    html = data.items.map(function(v,i) {
        return '
    ' + v.title + '
    ' + '

    By: ' + v.author + '

    '; }).join(''); div.innerHTML = html;

    JSFIDDLE DEMO


    @Xeon06 shows how in his answer using createElement(), which is arguably a better approach.

    Here's how I'd 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 modify it to use a for statement instead:

    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 benefit of using a documentFragment is that you can do a single append to the DOM via the fragment instead of multiple appends. This gives better performance, especially if you have a large set of data.

提交回复
热议问题