检查是否存在具有相同类的多个元素

时间:2014-05-17 12:27:26

标签: jquery

想知道是否有办法检查文档中是否存在具有相同类的元素。

例如:

<div class="panel">panel 1</div>
<div class="panel">panel 2</div>
<div class="panel">panel 3</div>

JS:

if ( $('.panel')[0] ) {
    console.log('exists')
}

..但我想检查是否存在多于一个panel元素,更改2.

3 个答案:

答案 0 :(得分:17)

尝试使用length属性来完成任务,

if($('.panel').length > 1) {
  console.log('yes, more than one element exist')
}

答案 1 :(得分:3)

if ( $('.panel').length >= 2 ) {
    console.log('exists')
}

这应该有效

答案 2 :(得分:1)

只需使用length属性;)

if ($('.panel').length > 0) {
  // your code
}