Frizzant
Frizzant

Reputation: 768

Get Index of Element with specific (unique) class in HTMLCollection

In the Title.

HTML:

<div class="active"></div>
<div></div>
<div></div>

Javascript (Vanilla):

// source HTML collection, only get the elements index which has the class "active"
let theCollection = document.querySelectorAll('div'); 

// related HTML collection
let anotherCollection = document.querySelectorAll('div .anotherClass');
// adding the class the corresponding element
theCollection[index].classList.add('active');

What I need to get is the index of the element which currently has the active class within theCollection.

Upvotes: 1

Views: 852

Answers (2)

Liad Yogev
Liad Yogev

Reputation: 874

If I unserstood correctly, you want to append the active class to the div that comes after the div who has the active class.

Why not just select all the corresponding divs and directly add the active class to them?

document.querySelectorAll('div.active + div').classList.add('active'); // selects all the div that comes after divs who have the .active class

Upvotes: 0

colecmc
colecmc

Reputation: 3318

To accomplish your task:

"What I need to get is the index of the element which currently has the active class within theCollection."

you can loop over the divs and check to see which div has the active class. Please run the code to verify.

document.querySelectorAll('div').forEach((item, index) => {
  if (item.classList.contains('active')) {
    document.getElementById('showActiveIndex').textContent = `index is ${index}`;
  }
})
<div>zero</div>
<div>one</div>
<div class="active">two</div>
<div>three</div>
<hr />
<div id="showActiveIndex"></div>

Upvotes: 1

Related Questions