I’m trying to insert using Vanilla Javascript to insert a node before a H2 tag. I thought insertBefore was what I want but I may be wrong.
const nodes = document.getElementsByTagName("h2");
divMove = document.createElement("div");
divMove.className = "contents";
nodes[0].insertBefore(divMove, nodes[0]);
What javascript command should I use to insert a div before the first h2 on a page. Any help is appreciated. Its to occur on multiple pages where there h2 id won’t be the same.
3
Answers
Your code is close. The missing bit is that
Node.insertBefore()
is a method that needs to be called on the parent node of the target:You can shorten the exercise by using
element.insertAdjacentHTML()
:You can use
Element#before
instead, which is more convenient and intuitive. This method directly inserts nodes before the specified element; there is no need to consider the parent at all.