Finding the index of the element with class in native Javascript

怎甘沉沦 提交于 2019-12-23 21:11:11

问题


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.


回答1:


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.




回答2:


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).




回答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!



来源:https://stackoverflow.com/questions/19784453/finding-the-index-of-the-element-with-class-in-native-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!