Search code examples
javascripthtmlecmascript-6htmlcollection

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.


Solution

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