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.