A good[ish] website
Web development blog, loads of UI and JavaScript topics
Adding element after and before other elements in the DOM, also known as appending or prepending. Pure JavaScript provides some handy methods for that.
If you’ve used jQuery, you might know append()
and prepend()
methods, here’s how to do that with native JavaScript.
The appendChild
method will put the source element inside the target element, in the last position, after all of the pre-existing elements.
The below example will:
#box
jack
jack
in the #box
const box = document.getElementById('box')
const jack = document.createElement('div')
jack.innerHTML = 'Jack!'
box.appendChild(jack)
That would give us the following HTML:
<div id="box">
<p>Lorem ipsum...</p>
<div>Jack!</div>
</div>
There’s a rule: the same node can’t be present twice in the DOM, this means that if an existing element is appended, it will be removed from it’s original position. So in that case it’s more like a move command. If this is not desired, try the .cloneNode()
instead.
There’s no prependChild
, but prepending can be done using the insertBefore()
.
The steps are the same as above, expect the last line. You need to give insertBefore
3 things:
box
jack
element.firstChild
const box = document.getElementById('box')
const jack = document.createElement('div')
jack.innerHTML = 'Jack!'
box.insertBefore(jack, box.firstChild)
Performance is of course completely unimportant, unless you deal with millions of iterations. But anyway, the native methods are much faster than jQuery .append()
.
Higher the dongle === faster:
Both of these methods are pretty solid and they work in all browsers.
Comments would go here, but the commenting system isn’t ready yet, sorry.