Creating DOM-elements is pretty straight forward, it is just very explicit and will take some getting used to.
In its most basic use you need three methods:
createElement: creates an element (e.g. <div>)
createTextNode: creates text content for use in elements
appendChild: add a DOM-Node (such as an element or text) to another node
Creating new elements is always a document operation (oversimplification: the document is the HTML-tree of a webpage). So you always use document.create*, while the actual appending of those elements is done through the elements that should contain those newly created elements.
Now that I've mentioned these native DOM methods, lets put them to use and create an unordered list containing all user information.
var retailerData = {
"del": {
"zip": "",
"city": ""
},
"user": {
"country": "Denmark",
"phone": "0000",
"nbrOrders": 0,
"name": "John doe",
"salesPerson": "Frederik Jensen",
"customerNo": "5464564564",
"email": "[email protected]"
},
"order": {
"shippingSum": 0.0,
"orderno": "",
"voucher": "",
"currency": "",
"orderVat": 0.0,
"orderSum": 0.0,
"items": []
}
}
// create an <ul> element and add it to the <body>
var ul = document.body.appendChild(document.createElement('ul')),
key, li;
for (key in retailerData.user) {
// create a <li> element and add it to the <ul>
li = ul.appendChild(document.createElement('li'));
// create a <span>, which is added to the <li> and immediately put text
// into it (appendChild returns the appended child), this practice is
// known as 'chaining'
li.appendChild(document.createElement('span'))
.appendChild(document.createTextNode(key));
// now add the value to the <li>, it will end up after the <span> we
// created above
li.appendChild(document.createTextNode(retailerData.user[key]));
}
li span {
display: inline-block;
width: 8em;
font-style: italic;
}
var ul = document.body.appendChild(document.createElement('ul')),
key, li;
for (key in retailerData.user) {
li = ul.appendChild(document.createElement('li'));
li.appendChild(document.createElement('span'))
.appendChild(document.createTextNode(key));
li.appendChild(document.createTextNode(retailerData.user[key]));
}
The above snippet as working fiddle
In jQuery, the syntax is more convenient (this is one of the reasons it has become so popular)
var $ul = $('body').append('<ul>');
$.each(retailerData.user, function(key, value) {
$ul.append('<li><span>' + key + '</span>' + value + '</li>');
});
A working fiddle demonstrating jQuery.
document.createElement('div'), add any data to the element(s) and append it to the DOM.retailerData.del.ziporretailerData.user.country, for example.