The latter ( appendChild ) does not cause a complete rebuild of the DOM or even all elements / nodes within the target.
The first (setting innerHTML ) really causes a complete rebuild of the contents of the target element, which, if you add, is not required.
By adding via innerHTML += content , the browser browses all the nodes in the element, creating an HTML string to convey the JavaScript level. Then your code adds text to it and sets innerHTML , forcing the browser to delete all old nodes in the target object, reanalyze all this HTML and build new nodes. Therefore, in this sense, it can be inefficient. (However, HTML parsing is what browsers do, and they really, really fast on it.)
Setting innerHTML really cancels out any references to elements in the target element that you can hold because these elements no longer exist, you deleted them and then added new ones (which look very similar) when you set innerHTML .
In short, if you add, I would use appendChild (or insertAdjacentHTML , see below). If you are replacing, there are very correct situations where using innerHTML is a better option than creating the tree itself through the DOM API (speed is central among them).
Finally, it is worth mentioning insertAdjacentHTML , which is a function that you can use to insert nodes and elements into or near an element using an HTML string. You can add an element to it: theElement.insertAdjacentHTML("beforeend", "the HTML goes here"); The first argument is the placement of the HTML; your choices are "beforebegin" (outside the element, right in front of it), "afterbegin" (inside the element at the beginning), "beforeend" (inside the element, at the end) and "afterend" (outside the element, immediately after it). Note that "afterbegin" and "beforeend" are inserted into the element itself, while "beforebegin" and "afterend" are inserted into the parent element. Supported by all major desktop browsers, I have no idea how good mobile support is (although I'm sure iOS Safari and Android 2.x at least have this, but the gasket is tiny.
TJ Crowder Feb 21 '10 at 11:18 2010-02-21 11:18
source share