Home > other >  Adding a class to elements depending on their length
Adding a class to elements depending on their length

Time:10-31

I'm trying to loop through elements and check their length, then add a class if parents have more than 2 elements.

Now the class is been added to all parent elements.

My code is like this:

let CheckOptions = [...document.querySelectorAll(".value select option")]
let checkSelects = [...document.querySelectorAll(".value select")]


checkSelects.forEach(checkSelect => {
  if(CheckOptions.length >= 2){
    CheckOptions.forEach(checkSelects => checkSelect.classList.add("active"));
  }
})
.active {
  background-color: red;
<div >
    <select >
        <option >1</option>
        <option >2</option>
        <option >3</option>
        <option >4</option>
    </select>
  </div>

<div >
    <select >
        <option >1</option>
        <option >2</option>
    </select>
  </div>

<div >
    <select >
        <option >1</option>
        <option >2</option>
        <option >3</option>
        <option >4</option>
    </select>
  </div>

What I'm doing wrong here?

CodePudding user response:

We can access a select's options by the options select property so we check the length of that property's value is greater than 2, if so, we add the class active to the current select.

Try the following .js code:

let checkSelects = [...document.querySelectorAll(".value select")]

checkSelects.forEach(checkSelect => {
  const options = checkSelect.options
  if (options.length > 2) {
    checkSelect.classList.add("active")
  }
})

Also, in order to get the length, instead of getting the options property of the checkSelect, you can just get the length by checkSelect.length property.

So it would be:

let checkSelects = [...document.querySelectorAll(".value select")]

checkSelects.forEach(checkSelect => {
  if (checkSelect.length > 2) {
    checkSelect.classList.add("active")
  }
})
  • Related