简体   繁体   中英

Javascript how to append an element to div with specific class

I have some <div> s where I want to append some data to a child div with a specific class but I'm not sure how to do that:

Here is my JS code:

let items = document.querySelectorAll(".item");
items.forEach(function (item) {

  let textnode = document.createElement('p');
  textnode.innerHTML = 'some text';
  item.appendChild(textnode);
});

This actually works, bu it only appends the "textnode"-element to the existing elements.

When I try:

document.getElementsByClassName('left').appendChild(textnode);

It doesn't work.

Here is a JSFIDDLE

EDIT

I want to append the data to the .left element

getElementsByClassName returns multiple elements. Class names are not unique. Therefore you first need to select an element in that list.

 var textnode = document.createTextNode("Test"); var node = document.getElementsByClassName('left'); node[0].appendChild(textnode);
 <div class="left"></div>

It seems you want to append an element to .left descendant of item elements. If this is the case, you can use the querySelector instead of getElementsByClassName :

item.querySelector('.left').appendChild(textnode);

Note that above code calls the querySelector method as a member of item (instance ofHTMLDivElement interface).

getElementsByClassName returns the array of elements. So u need to use the index for that.

let x = document.getElementsByClassName('left')
x[0].appendChild(textnode)

This is working. I have updated the code in your fiddle. Please check out

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