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
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,.innerHTMLhas 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 theinnerHTMLproperty is that you have to build that HTML from yourJSONrepresentation anyway, which will also take time. Since you have to process theJSONobject, using the DOM manipulation methods is a sensible design approach.