I want to find the nu" />
I want to find the nu" />
I want to find the nu"/>

How to find the number of times a specific classname showed up before an element?

48 Views Asked by At

Lets say i had something like this.

<div class="apple"></div>
<div class="apple"></div>
<div class="apple" id="MyElement"></div>

I want to find the number of times another element with class="apple" had shown up before the element with id="MyEement" so i can modify it on javascript later with document.getElementsByClassName("class")[unknown]. is there a way to do this with absolute no jQuery?

I could allways count the number of elements before it with class=apple, but i have a lot of elements with that classname, so is there a way to do this programaticly

1

There are 1 best solutions below

1
Mehdi On BEST ANSWER

use directly the elements array to search for the element with the ID "MyElement" using the findIndex method. The index returned by findIndex is the position of the element within the elements array, so we can use it directly to determine how many "apple" elements came before the element with ID "MyElement".

// Get all elements with the class name "apple"
const elements = document.getElementsByClassName("apple");

// Find the index position of the element with the ID "MyElement"
const myElementIndex = Array.prototype.findIndex.call(elements, (element) => element.id === "MyElement");

// Determine how many "apple" elements came before the element with ID "MyElement"
const numApplesBefore = myElementIndex;

console.log(numApplesBefore); // outputs: 2