-
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>
-
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>
-
Thanks a bunch!
What are the best resources to learn this language?