Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Append to HTMLcollection of nodes

Why does this not work?

var nodes = document.getElementsByClassName("abc");
nodes += document.getElementsByClassName("xyz");

Second line corrupts nodes variable. Classes exist in the HTML page. Any way to have this working?


1 Answers

There's no way to append to HTMLCollection. https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection

You can however, convert it to array and join them.

var nodes = document.getElementsByClassName("abc");
var nodes2 = document.getElementsByClassName("xyz");


var nodeList = []
  .concat(Array.from(nodes))
  .concat(Array.from(nodes2));

console.log(nodeList);
<script src="https://cdn.polyfill.io/v2/polyfill.min.js"></script>
<div class="abc">1</div>
<div class="abc">2</div>
<div class="abc">3</div>

<div class="xyz">4</div>
<div class="xyz">5</div>
like image 185
Chybie Avatar answered Jun 17 '26 20:06

Chybie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!