-1

I am trying to develop a reusable accordion component where I have to find all the accordion items which are giving me HTMLCollection which seems like an Array form but if you go and try to manipulate with some methods like forEach then you will get an error.

I am looking for the easiest and most optimized way around fixing such issues while using pure JavaScript.

Code example:

HTML

<div classs="container">
    <div id="accordion">
        <div class="accordion-item">...</div>
        <div class="accordion-item">...</div>
        <div class="accordion-item">...</div>
    </div>
</div>

JavaScript

var accordion_el = document.getElementById("accordionExample"),
    accordion_items = document.getElementsByClassName("accordion-item");

// below code will give error
accordion_items.forEach(function (item) {
    console.log(item);
});

I tried with toArray() but that failed.

What worked for me:

  • Array.from()
  • Similarly, [...document.getElementsByClassName("accordion-item")] too

I have a question about the best performance optimization to take a minimum time for the DOM manipulation if have multiple instances of the same component on a page.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Kushal Jayswal
  • 925
  • 1
  • 12
  • 31

1 Answers1

3

You can use spread syntax to convert to an array.

accordion_items = [...document.getElementsByClassName("accordion-item")];

However, you can directly use document.querySelectorAll here, which returns a NodeList that has a forEach method.

document.querySelectorAll(".accordion-item").forEach(item => console.log(item));
<div id="accordion">
  <div class="accordion-item">...</div>
  <div class="accordion-item">...</div>
  <div class="accordion-item">...</div>
</div>
Unmitigated
  • 76,500
  • 11
  • 62
  • 80