Yesterday we had a look at how you can insert an element before another element.
And today, we'll be looking at the after function to insert elements after another element.
Insert an element after another element
Let's start with an existing element with a unique ID.
<div id="existing">I'm an existing element</div>
const el = document.getElementById('existing');
const p = document.createElement('p'); p.textContent = `Hi I'm new here`; // Insert before the after element el.after(p);
And just like the before function, we can use a simple one-liner to change the text of this after insert.
// Insert element and text el.after(span, "I'm a new span");
You can view this code on Codepen.