I have the following javascript:
// create a new article tag
var elem = document.createElement('article');
// append the article to the comments list
document.querySelector('#comments-list').appendChild(elem);
I want to set the content of the article, and add some classes to it too so I'm looking at two ways of doing this:
// Option 1
// set the content using .innerHTML()
// and add the classes manually to the classList
elem.innerHTML = "This is the comment";
elem.classList.add('comment');
// Option 2
// set the content and classes in one go using .outerHTML()
elem.outerHTML = "<article class='comment'>This is the comment</article>";
Both work great, but I notice that .innerHTML
needs to be called before the element is appended to the DOM, wheras outerHTML
needs to be called after it added to the DOM.
I prefer the second option because I'm actually rendering Rails partials in this javascript file, and there's a nuanced case where it is preferable.
My question is whether one of these techniques is better than the other? Is is a problem to add an element to the DOM and then change it's HTML afterwards? Or is it better from a perfomance standpoint to set innerHTML before writing to the DOM?