How to Prepend a Child Element to a Div Using JavaScript?

Estimated read time 1 min read

To prepend a child element to a div using JavaScript, you can use the insertBefore() method on the parent div element. The method allows you to insert a new child element before the first child of an element. Here’s an example:

const parentDiv = document.querySelector("#parent");
const newChild = document.createElement("p");
newChild.textContent = "This is a new child element.";
parentDiv.insertBefore(newChild, parentDiv.firstChild);

In the example above, the parent div element is selected using document.querySelector("#parent"). The createElement() method is used to create a new p element, and the text content of the element is set using textContent. Finally, the insertBefore() method is used to insert the new p element as the first child of the parent div. The new child will be added before any other child elements that may exist in the parent div.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply