Reputation: 67
I'm trying to iterate over elements with the same class in order to see if within a specific element a button has a specific class. I understand how this would be done in jQuery however the project does not have jQuery, so this has to be done with vanilla JS...which I'm not as familiar with.
let boardItems = document.getElementsByClassName("item--product");
for (let i = 0; i < boardItems.length; i++) {
if(boardItems.children.classList.contains('board-item-selected')){
console.log(i);
}
}
what I'd like is to get the index number of each item that does contain the class in the child.
Upvotes: 0
Views: 3516
Reputation:
Convert the HTMLCollection
into an array of HTMLElement
and parse the class list of each element.
let htmlCollection = document.getElementsByClassName("item--product");
let array = [].slice.call(htmlCollection)
for (let i = 0; i < array.length; i++) {
if(array[i].classList.contains("board-item-selected")){
console.log("The index of the board-item-selected: " + i)
}
}
<div class="item--product"></div>
<div class="item--product"></div>
<div class="item--product board-item-selected"></div>
<div class="item--product"></div>
<div class="item--product board-item-selected"></div>
<div class="item--product"></div>
<div class="item--product"></div>
Upvotes: 1
Reputation: 136
You're accessing the entire list not the array.
Try change line 3 to if(boardItems[i].classList.contains('board-item-selected')) {
Upvotes: 0