Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is better for DOM manipulation - the DOM API or innerHTML?

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.)

like image 259
yilmazhuseyin Avatar asked Dec 29 '22 09:12

yilmazhuseyin


1 Answers

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"')
]);
like image 120
slebetman Avatar answered Dec 31 '22 00:12

slebetman