使用本机Javascript中的类查找元素的索引 [英] Finding the index of the element with class in native Javascript

查看:126
本文介绍了使用本机Javascript中的类查找元素的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法获取类名的索引(即第3个元素的类className是3而不使用jQ?

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?

我不知道知道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.

谢谢。

BTW,我使用了jQ而不是拼写出来,所以如果有人有同样的问题,这些结果可以在Google中过滤掉。我把它拼出来了,有人在谷歌使用NOT运算符,这个也会消失。

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.

推荐答案

你可以用 document.getElementsByClassName

var el = document.getElementsByClassName('className');
for (var i = 0; i < el.length; i++) {
   // your index is inside here
}

el [i] 是当前迭代中的元素, i 是索引

el[i] is the element in the current iteration, i is the index


(即类className的第三个元素是3)

(I.e. the third element with the class "className" would be 3)



if (i == 3)
return el[i]






JsFiddle:此处

这篇关于使用本机Javascript中的类查找元素的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆