Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the index of the element with class in native Javascript

Is there a way to get the index of class name (I.e. the third element with the class "className" would be 3 without using jQ?

I don't know jQ, and I don't have time to learn it right now, and I don't want to include code into my code that I don't understand at least some.

Thanks.

BTW, I've used jQ instead of spelling it out so those results can be filtered out in Google should somebody have the same question. If I spelled it out, and somebody used the NOT operator in Google, this one would also disappear.

like image 317
David Avatar asked Nov 29 '22 15:11

David


1 Answers

You could do something like:

// the element you're looking for
var target = document.getElementById("an-element");

// the collection you're looking in
var nodes = document.querySelectorAll(".yourclass");

var index = [].indexOf.call(nodes, target);

See: Array's indexOf. If you have already a proper array as nodes instead of a NodeList, you can just do nodes.indexOf(target).

like image 80
ZER0 Avatar answered Dec 10 '22 03:12

ZER0