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.
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);
}
});
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
document.querySelectorAll(".yourClassNameHere")
dot and your class name. or document.querySelectorAll("#yourIdNameHere")
# and your ID name
Commented
Aug 26, 2020 at 12:09