Skip to content
Advertisement

JavaScript | appendChild to all classes

I have problem with append Child to whole classes in my document which the name of class is “onbackorder”. Here is my code:

<script>
    var first = document.createElement("p");
    var text = document.createTextNode("On backorder");
    first.appendChild(text);

    var isRequestQuote = document.getElementsByClassName('onbackorder');
    if (isRequestQuote.length > 0) {
        document.querySelector(".onbackorder").appendChild(first);
    }
</script>

For this moment function put selector randomly. How can I get same selector in whole document where class is “onbackorder”.

Thank you

Advertisement

Answer

There are 2 points:

  1. document.querySelector(".onbackorder") is just return first item. So you need to use document.querySelectorAll('.onbackorder').

The Document method querySelector() returns the first Element within the document that matches the specified selector, or group of selectors. If no matches are found, null is returned.

https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector

  1. var first = document.createElement("p"); you have to create multiple reference variable to append to each onbackorder item. Because you cannot create only one and append to multiple items.

So I modified your code and make it works. You can check it at below:

var first = document.createElement("p");
var text = document.createTextNode("On backorder");
first.appendChild(text);

const allBackOrders = document.querySelectorAll('.onbackorder');
allBackOrders.forEach((item) => {
  var newItem = first.cloneNode(true);
  item.appendChild(newItem);
});
<div class="onbackorder"></div>
<div class="onbackorder"></div>
<div class="onbackorder"></div>
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement