skip to Main Content

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


  1. 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:

    The insertBefore() method of the Node interface inserts a node before a reference node as a child of a specified parent node.

    const nodes = document.getElementsByTagName("h2");
    divMove = document.createElement("div");
    divMove.textContent = "div text";
    nodes[0].parentNode.insertBefore(divMove, nodes[0]);
    //      ^^^^^^^^^^^
    <div>
      <h2>First</h2>
      <h2>Second</h2>
    <div>
    Login or Signup to reply.
  2. You can shorten the exercise by using element.insertAdjacentHTML():

    document.querySelector("h2").insertAdjacentHTML("beforebegin",`<div class="contents">This is the inserted div.</div>`);
    <H2>My heading</H2>
    <H2>Another heading</H2>
    Login or Signup to reply.
  3. 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.

    const div = document.createElement('div');
    div.className = 'contents';
    div.textContent = 'div text';
    document.querySelector('h2').before(div);
    <h2>h2 title</h2>
    <h3>h3 title</h3>
    <h2>another h2 title</h2>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search