【发布时间】:2013-03-25 18:16:23
【问题描述】:
我想知道样式class 是否存在,如果存在,有多少个元素。
要知道样式 class 是否存在,我使用:
if ($("*").hasClass('ui-state-active')) {
alert("class exist : "+nb_checked);
}
但要知道类有多少元素,我想不通。
【问题讨论】:
标签: javascript jquery html css dom
我想知道样式class 是否存在,如果存在,有多少个元素。
要知道样式 class 是否存在,我使用:
if ($("*").hasClass('ui-state-active')) {
alert("class exist : "+nb_checked);
}
但要知道类有多少元素,我想不通。
【问题讨论】:
标签: javascript jquery html css dom
这是一种更简单的方法:
$('.ui-state-active').length
【讨论】:
只要做:
$('.ui-state-active').length
【讨论】:
if($('.ui-state-active').length){
alert("class exist : "+$('.ui-state-active').length);
}
文档在这里:
【讨论】:
你可以同时使用它
c = $('.ui-state-active').length;
if (c>0) {
console.log('There is '+c+' elements having required class');
}
【讨论】:
使用jQuery,你可以直接select all elements 里面有某个类。其语法与 CSS 选择器的语法相同:
$(".className")
这将创建一个jQuery object,它是匹配元素的集合。这个对象有很多有用的属性,其中之一是length,集合中元素的数量。
在您的情况下,找到所需元素的数量就像
$(".ui-state-active").length
【讨论】:
你可以同时做到这两点:
var elements = $('.ui-state-active');
if(elements.length === 0) {
alert('No elements with class ui-state-active!')
} else {
alert(elements.length + ' elements with class ui-state-active');
}
【讨论】:
怎么样:
$(".ui-state-active").length;
【讨论】: