Reputation:
I have this code:
try {
var _o, _l, i, _d = new Array(), _c;
_o = JSON.Parse( Request.Response );
for ( i = 0, _l = _o.length; i < _l; i++ ) {
_d[ i ] = document.createElement('div');
_c = document.getElementById('comentsContainer');
_c.removeChild( _c.firstChild );
_d[ i ].className = 'comment-user';
_c.appendChild( _d [i] );
}
}
catch ( w ) {
console.log( w );
}
The question is, is it better this way or should I use innerHTML ?
ADD: the object to parse :
"comments" : [
{ "user" : "foo", "comment" : "foo", "date" : "foo/foo/bar", "id_comment" : "bar" },
{ /* the same as above x10 */ }
]
Note that I want to parse each object from each array to a DOM element
Upvotes: 3
Views: 1767
Reputation: 25332
I would say that DOM
manipulation is a cleaner approach: innerHTML
is a bit spaghetti code
, where you mix the markup language with behavior (JavaScript), and you don't have a clear structure at the end. In addition, in most of the modern browsers DOM API
are faster or equivalent to innerHTML
in term of performance – unfortunately IE and Opera are not the case:
http://jsperf.com/innerhtml-or-dom/4
So, go for the DOM APIs
, maybe you could clean and optimize a bit your code (e.g. you don't need to execute getElementById
every loop to get the commentsContainer reference, you can have it outside; also not sure why you remove the first child every time you add a comment, seems to me that you could likely remove the comment you added previously, in that case can be optimized as well).
Upvotes: 1
Reputation: 13293
Since you already have a structural representation of the data here (rather than raw HTML to parse), I'd say that your approach (using DOM manipulation methods) makes more sense than using an approach built around .innerHTML
. In some cases, .innerHTML
has shown to be a performance win, but I'm not sure that's a case on modern browsers with decent JavaScript engines. Furthermore, a lot of the gain you might get from dropping a blob of HTML into the innerHTML
property is that you have to build that HTML from your JSON
representation anyway, which will also take time. Since you have to process the JSON
object, using the DOM manipulation methods is a sensible design approach.
Upvotes: 2