0

I want to add an element directly after a certain element on a web page using JavaScript.

I also want to add it after every occurrence of this certain element.

0

2 Answers 2

0

Use Node.insertBefore() and Document.querySelectorAll().

Say you want to add an element div after each div with the class .after-me:

const elements = document.querySelectorAll("div.after-me");

elements.forEach((e) => {
    const newNode = document.createElement("div");
    const nextSibling = e.nextSibling;
    if (nextSibling === null) {
        e.parentNode.appendChild(newNode);
    } else {
        e.parentNode.insertBefore(nextSibling, newNode);
    }
});
0

In JavaScript you can do it like this

  <div></div>
  <div></div>
  <div></div>

  <script>
    let div = document.querySelectorAll("div");
    let para = document.querySelectorAll("div");    
    let p = document.createElement("p")

    div.forEach((d => {    
      d.append(p)
    }))

    para.forEach((p => {    
      p.append("Hello World")
    }))
 </script>

We are getting all <div>s and then for each one we are are appending a <p> then we get all <p>s and for each one we are appending the words hello world.

In jQuery you can do it like this

  <div></div>
  <div></div>
  <div></div>

  <script
    src="https://code.jquery.com/jquery-3.5.1.min.js"
    integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
    crossorigin="anonymous"></script>
  <script>
    $( "div" ).append( "<p>Hello World</p>" );    
  </script>

This is shorter as jQuery finds all <div>s and appends the <p> and text all in one line

2
  • Does querySelectorAll work for class name, it turns out I need to getelemenybyclassname and append each. Commented Aug 25, 2020 at 21:57
  • Yes you can do document.querySelectorAll(".yourClassNameHere") dot and your class name. or document.querySelectorAll("#yourIdNameHere") # and your ID name Commented Aug 26, 2020 at 12:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.