简体   繁体   中英

Add a paragraph in multiple html elements that are the same using javascript

I am trying to add <p>Hello World</P> , using javascript, in two div elements in html that are the same.

So I have this div elements :

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

What I tried is this :

let p = document.createElement('p'); p.textContent = "Hello World"; document.querySelectorAll("div").forEach((divElement) => {element.appendChild(p);})

But it only adds it to one of the div elements, how can I make it so that I have it in both div elements ? no jquery please

Actually there are 2 problems: the first is that you are using the same ID for multiple elements, the second is that you are creating a single DOM object for more than one element. You can solve it by using classes and creating a paragraph each time you want to append it.

EDIT: This answer provide an explanation of why you cannot append the same child twice: explanation

 document.querySelectorAll(".test").forEach((el) => { let p = document.createElement('p'); p.textContent = "Hello World"; el.appendChild(p); })
 <div class="test"></div> <div class="test"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM