Subscribe

JavaScript insert newly created element after another element

โœ๏ธ

How to add a new element after an existing element

13 Jun, 2021 ยท 1 min read

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>

Let's select this element using its ID in JavaScript.

const el = document.getElementById('existing');

And now we can create a new element using the JavaScript createElement function.

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.

See the Pen JavaScript insert newly created element after another element by Chris Bongers ๐Ÿค“๐Ÿ’ปโšก๏ธ (@dailydevtips1) on CodePen.

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next ๐Ÿ“–

TypeORM viewEntity

30 Mar, 2022 ยท 5 min read

TypeORM viewEntity

The Record Utility Type in TypeScript

12 Mar, 2022 ยท 3 min read

The Record Utility Type in TypeScript

Join 1513 devs and subscribe to my newsletter