Categories
JavaScript Answers

How to implement prepend and append elements with regular JavaScript?

Spread the love

Sometimes, we want to implement prepend and append elements with regular JavaScript.

In this article, we’ll look at how to implement prepend and append elements with regular JavaScript.

How to implement prepend and append elements with regular JavaScript?

To implement prepend and append elements with regular JavaScript, we use appendChild to append and insertBefore to prepend.

For instance, we write

const theParent = document.getElementById("theParent");
const theKid = document.createElement("div");
theKid.innerHTML = "Are we there yet?";

theParent.appendChild(theKid);
theParent.insertBefore(theKid, theParent.firstChild);

to get the theParent element and create the theKid element with createElement.

Then we call theParent.appendChild with theKid to append the theKid as the last child of theParent.

And we call theParent.insertBefore with theKid and theParent.firstChild to prepend theKid as the element before the first child element of theParent.

Conclusion

To implement prepend and append elements with regular JavaScript, we use appendChild to append and insertBefore to prepend.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *