用jQuery获取元素的类列表 [英] Get class list for element with jQuery

查看:72
本文介绍了用jQuery获取元素的类列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


$ b

ex

$ jQuery中有没有一种方法可以循环访问或将数组赋值给一个数组? b
$ b

 < div class =Lorem ipsum dolor_spec sit amet> Hello World!< / div> 

我将在上面的dolor_spec中寻找一个特殊类。我知道我可以使用hasClass(),但实际的类名不一定是当时已知的。

解决方案

您可以使用 document.getElementById('divId')。className.split(/ \ s + /); 来获得一个类名称数组。 b

然后你可以迭代并找到你想要的。

  var classList = document.getElementById 'DIVID')className.split(/ \s + /); 
for(var i = 0; i< classList.length; i ++){
if(classList [i] ==='someClass'){
//做某事
}
}

jQuery并没有真正帮助您在这里...


$ b $

  var classList = $('#divId')。attr('class')。split(/ \ s + /); 
$ .each(classList,function(index,item){
if(item ==='someClass')){
//做某事
}
} );


Is there a way in jQuery to loop through or assign to an array all of the classes that are assigned to an element?

ex.

<div class="Lorem ipsum dolor_spec sit amet">Hello World!</div>

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.

解决方案

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 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屋!

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