使用 jQuery 获取元素的类列表 [英] Get class list for element with jQuery
本文介绍了使用 jQuery 获取元素的类列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 jQuery 中有没有办法循环遍历或将分配给元素的所有类分配给数组?
Is there a way in jQuery to loop through or assign to an array all of the classes that are assigned to an element?
例如
<div class="Lorem ipsum dolor_spec sit amet">Hello World!</div>
我将在上面的dolor_spec"中寻找一个特殊"类.我知道我可以使用 hasClass() 但当时可能不一定知道实际的类名.
I will be looking for a "special" class as in "dolor_spec" above. I know that I could use hasClass() but the actual class name may not necessarily be known at the time.
推荐答案
您可以使用 document.getElementById('divId').className.split(/s+/);
来获得类名数组.
You can use document.getElementById('divId').className.split(/s+/);
to get you an array of class names.
然后你可以迭代并找到你想要的.
Then you can iterate and find the one you want.
var classList = document.getElementById('divId').className.split(/s+/);
for (var i = 0; i < classList.length; i++) {
if (classList[i] === 'someClass') {
//do something
}
}
jQuery 在这里并没有真正帮助您...
jQuery does not really help you here...
var classList = $('#divId').attr('class').split(/s+/);
$.each(classList, function(index, item) {
if (item === 'someClass') {
//do something
}
});
这篇关于使用 jQuery 获取元素的类列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文