I have the following code:
tr = document.createElement("tr");
root.appendChild(tr);
td = document.createElement("td");
td.appendChild(document.createTextNode("some value"));
tr.appendChild(td);
Well, this code is same as
root.innerHTML = "<tr><td>some value</td></tr>";
The first version is probably a better way to go, because the browser does not have to render a string. But it is too long. Especially for bigger structures, this implementation is becoming really hard to read. So I felt like there is a better way to write this (without any JavaScript library). How would you implement this so the code would be more readable? (Right now I am separating code with comments.)
You could always write wrapper functions around the clunky DOM API to make the code more readable. I usually use something like:
function newElement (type,attr,children) {
var el = document.createElement(type);
for (var n in attr) {
if (n == 'style') {
setStyle(el,attr[n]); /* implementation of this function
* left as exercise for the reader
*/
}
else {
el[n] = attr[n];
}
}
if (children) {
for (var i=0; i<children.length; i++) {
el.appendChild(children[i]);
}
}
}
function newText (text) {
document.createTextNode(text);
}
Then your can write much more declarative code:
var tr = newElement('tr',{},[
newElement('td',{},[
newText('some value')
])
]);
Just remember the differences between css and javascript:
var div = newElement('div',{
className:'foo',
style:{
marginLeft:'10px'
}
},[
newText('notice we use "className" instead of class" '+
'and "marginLeft" instead of "margin-left"')
]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With