How to dynamically populate html elements with JSON data using Javascript rather than jQuery?

I have the following snapshot of JSON data:

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

How to 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 to accomplish this using Javascript, not jQuery.

+6
source share
7 answers

Scroll 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 them, you are really better off using jQuery.

+10
source
 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 the 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 would suggest using the identifier instead of the class for the news-story element, so you can use getElementById instead (if, of course, you have several).

If this is not possible, you can use the compatibility function from MDN for getElementsByClassName .


If you need to create internal elements, then here is one way:

 var div = document.getElementsByClassName('news-story')[0], data = JSON.parse( my_JSON_data ), html; html = data.items.map(function(v,i) { return '<h5>' + v.title + '</h5>' + '<p>By: ' + v.author + '</p>'; }).join(''); div.innerHTML = html; 

JSFIDDLE DEMO


@ Xeon06 shows how his answer uses createElement() , which is arguably the best approach.

Here's how I would 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 change it to use the for statement:

 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 advantage of using documentFragment is that you can make one addition to the DOM through a fragment instead of several additions. This gives better performance, especially if you have a large dataset.

+6
source

Better late than never ... I recently made a lib to do just that!

FragBuilder is a library. The usage is pretty simple: for the example you posted, you will need to change around JSON a bit to make it a little more semantic ...

 var frag = [{"items": [ { "title": "sample 1", "author": "author 1" }, { "title": "sample 2", "author": "author 2" } ]}]; 

will become

 var frag = [ { "childNodes" : [ { "childNodes" : [ { "textContent" : "sample 1" } ], "tagName" : "H5" }, { "childNodes" : [ { "textContent" : "By: author 1" } ], "tagName" : "P" }, { "childNodes" : [ { "textContent" : "sample 2" } ], "tagName" : "H5" }, { "childNodes" : [ { "textContent" : "By: author 2" } ], "tagName" : "P" } ], "className" : "news-story", "tagName" : "DIV" } ]; 

then you will create a DocumentFragment by calling FragBuilder(frag)

There is also a reverse function if it’s easier for you to create a template using HTML and then convert to JSON https://gist.github.com/2313580 (note that spaces between tags are not processed and will cause crashes)

+3
source

I found that the most reliable way to create DOM elements is to use the element.innerHTML property. Basically you will have a DIV or SPAN in place in place on the page where you want to render the new HTML. You will then get this space in javascripting with document.getElementById("DIV-ID") , and then set the innerHTML DIV property to the new HTML code that you will create from the JSON object. There are many other JavaScript functions for creating elements, but I found that they are not always reliable and do not always have the best cross-browser support.

http://www.w3schools.com/jsref/prop_html_innerhtml.asp

+1
source

Sample without jQuery:

 <html> <head> <title>test</title> </head> <body> <div class="news-story"> <h5>sample 1</h5> <p>By: author 1</p> <h5>sample 2</h5> <p>By: author 2</p> </div> <script type="text/javascript"> var json = { "items": [ { "title": "sample x", "author": "author x" }, { "title": "sample y", "author": "author y" } ] }; var bindDataToHTML = function(data, element) { var h5 = null; var p = null; h5 = element.getElementsByTagName("h5"); p = element.getElementsByTagName("p"); h5[0].innerText = data.items[0].title; h5[1].innerText = data.items[1].title; p[0].innerText = data.items[0].author; p[1].innerText = data.items[1].author; }; document.getElementsByClassName = function(cl) { var retnode = []; var myclass = new RegExp('\\b'+cl+'\\b'); var elem = this.getElementsByTagName('*'); for (var i = 0; i < elem.length; i++) { var classes = elem[i].className; if (myclass.test(classes)) { retnode.push(elem[i]); } } return retnode; }; // For sample purpose, let imagine this method is a callback // for a request that provides you with your json data var doRequest = function() { var data = json; var element = null; var x = document.getElementsByClassName("news-story"); if((null != x) && (0 < x.length)) { element = x[0]; } bindDataToHTML(data, element); }; (function() { doRequest(); })(); </script> </body> </html> 
+1
source

Try JsRender and JsViews or Mustache / ember

0
source
 $(document).ready(function () { loadfunctionAjax(); }); var loadfunctionAjax = function () { $.ajax({ type: 'GET', url: '/Site/SocialLink', contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { var HTML = ''; for (var i = 0; i < data.length; i++) { item = data[i]; HTML += '<li><a class="" target="_blank" href="' + item.FALink + '"><i class="fa ' + item.FAIcon + '"></i>' + item.Name + '</a ></li > '; } $('#footerSocialNav').append(HTML); } }); } 
0
source

Source: https://habr.com/ru/post/902669/


All Articles