DEV Community

Cover image for JavaScript insert newly created element after another element
Chris Bongers
Chris Bongers

Posted on • Originally published at daily-dev-tips.com

4

JavaScript insert newly created element after another element

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>
Enter fullscreen mode Exit fullscreen mode

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

const el = document.getElementById('existing');
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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");
Enter fullscreen mode Exit fullscreen mode

You can view this code 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

Neon image

Build better on Postgres with AI-Assisted Development Practices

Compare top AI coding tools like Cursor and Windsurf with Neon's database integration. Generate synthetic data and manage databases with natural language.

Read more →

Top comments (0)

Neon image

Next.js applications: Set up a Neon project in seconds

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started →

👋 Kindness is contagious

Dive into this insightful write-up, celebrated within the collaborative DEV Community. Developers at any stage are invited to contribute and elevate our shared skills.

A simple "thank you" can boost someone’s spirits—leave your kudos in the comments!

On DEV, exchanging ideas fuels progress and deepens our connections. If this post helped you, a brief note of thanks goes a long way.

Okay