23

Wonder if there's any way to check if elements with the same class exists in a document.

For example:

<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')
}

.. but I want to check if MORE THAN ONE panel element exists, alteast 2.

eozzy
  • 66,048
  • 104
  • 272
  • 428

3 Answers3

21

Try to use the length property to accomplish your task,

if($('.panel').length > 1) {
  console.log('yes, more than one element exist')
}
Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
3
if ( $('.panel').length >= 2 ) {
    console.log('exists')
}

This should work

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
Fonzy
  • 691
  • 3
  • 14
1

Simply use the the length property ;)

if ($('.panel').length > 0) {
  // your code
}
Jonathan Gruber
  • 151
  • 3
  • 5