Subscribe

JavaScript insert newly created element before another element

โœ๏ธ

How to add a new element before an existing element

12 Jun, 2021 ยท 1 min read

The other day we learned how to create a new element with JavaScript. And in this article, I'll show you how you can insert it before another element.

As a recap, we can create an element using the createElement function.

Insert an element before another element

First, we have to make a sample element we can target in JavaScript.

<div id="existing">I'm an existing element</div>

Now we can select this element based on its ID.

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

And now, let's create a paragraph element and add it before this one.

const p = document.createElement('p');
p.textContent = `Hi I'm new here`;

// Insert before the existing element
el.before(p);

There is also the option to create these new elements on the fly, passing an element and text in one go.

// Insert element and text
el.before(span, "I'm a new span");

You can view this code on Codepen.

See the Pen JavaScript insert newly created element before 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 ๐Ÿ“–

JavaScript sending data between windows

9 Sep, 2022 ยท 4 min read

JavaScript sending data between windows

Using the native payment request JavaScript API

9 Aug, 2022 ยท 8 min read

Using the native payment request JavaScript API

Join 1828 devs and subscribe to my newsletter