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 rig
Solution 1:
You could do something like:
// the element you're looking forvar target = document.getElementById("an-element");
// the collection you're looking invar 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)
.
Solution 2:
you can use document.getElementsByClassName
var el = document.getElementsByClassName('className');
for (var i = 0; i < el.length; i++) {
// your index is inside here
}
el[i]
is the element in the current iteration, i
is the index
(I.e. the third element with the class "className" would be 3)
if (i == 3)
return el[i]
JsFiddle: here.
Solution 3:
Just use getElementsByClassName
, it returns a list of elements with the specified classes.
elements = document.getElementsByClassName("test")
element = elements[2] //get the 3rd element
Hope this helps!
Post a Comment for "Finding The Index Of The Element With Class In Native Javascript"