0

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.

user1568811
  • 69
  • 1
  • 12
  • `.children` is a `NodeList`, not a `Node`. It doesn’t have a `classList`. Consider using [`filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter): e.g. `boardItems.filter((item) => item.classList.contains("board-item-selected")).forEach((item) => console.log(item));`. – Sebastian Simon Jul 19 '19 at 03:26
  • Um...if this is about collecting elements from the nested buttons by class or whatever (not sure of objective not clear) -- don't you think the HTML be included as well. Please read on how to create a [mcve]. – zer00ne Jul 19 '19 at 03:30
  • Sorry if I'm not being clear. What I'm trying to achieve is that if there's 5 items with the same class, I want to know which of those five has a child div that has a specific class. Is it 1 and 3, 2 and 5, just 4...1 2 3 4 5? – user1568811 Jul 19 '19 at 03:36
  • Possible duplicate of [NodeList object in javascript](https://stackoverflow.com/questions/5501433/nodelist-object-in-javascript) – Samuel Jul 19 '19 at 03:40
  • @user1568811 HTML post it. I refuse to read dribble -- code presented properly is better than going on and on about something with no real context. – zer00ne Jul 19 '19 at 03:43

2 Answers2

1

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>
0

You're accessing the entire list not the array.

Try change line 3 to if(boardItems[i].classList.contains('board-item-selected')) {

Ezray
  • 136
  • 8