So what I'm trying to do is parse XML data into a new DIV which has an ID of post, this will happen each time a post is added to the XML file (posts.xml).
I'm not sure if I'm overlooking something, but I can't get the XML Data to display/render.
XML:
<POSTS>
<POST>
<TITLE>Title 123</TITLE>
<AUTHOR>Bob Dylan</AUTHOR>
<CONTENT>BLAH BLAH BLAH</CONTENT>
</POST>
<POSTS>
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Blog</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="posts"></div>
<script src="main.js"></script>
</body>
</html>
Javascript (main.js):
(function () {
// Adds a DOM structure for each post.
function renderPosts(posts) {
// Get the DOM element that will contain the posts.
var postsDiv = document.getElementById("posts");
posts.forEach(function (post) {
// Create the DOM elements.
var postDiv = document.createElement("div"),
postTitleDiv = document.createElement("div"),
postAuthorDiv = document.createElement("div"),
postContentDiv = document.createElement("div");
// Set the content of each element.
postNameDiv.innerHTML = post.name;
postAuthorDiv.innerHTML = post.author;
postContentDiv.innerHTML = post.content;
// Set CSS classes on each div so they can be styled.
postDiv.setAttribute("class", "post");
postNameDiv.setAttribute("class", "post-title");
postAuthorDiv.setAttribute("class", "post-author");
postContentDiv.setAttribute("class", "post-content");
// Assemble the post div.
postDiv.appendChild(postTitleDiv);
postDiv.appendChild(postAuthorDiv);
postDiv.appendChild(postContentDiv);
// Add the post div to the container for posts.
postsDiv.appendChild(postDiv);
});
}
// Fetches the file "posts.xml"
function getPosts(callback){
// Fetch the xml file using XMLHttpRequest.
var request = new XMLHttpRequest();
// When the file has loaded,
request.onload = function () {
// parse the XML text into an array of post objects.
//var posts = XML.parse(request.responseXML);
// Pass the posts array to the callback.
callback(posts);
};
request.open("GET", "posts.xml", false);
request.send();
xmlDoc=xmlhttp.responseXML;
}
// The main program, which gets then renders posts.
getPosts(function (posts) {
renderPosts(posts);
});
}()); //End Main Function