24

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.

1
  • 3
    $('.panel').length > 1
    – Ram
    Commented May 17, 2014 at 12:29

3 Answers 3

22

Try to use the length property to accomplish your task,

if($('.panel').length > 1) {
  console.log('yes, more than one element exist')
}
2
  • Thats what I meant, it would return true even if just one .panel exists, I want to check if multiple element with the same class exists
    – eozzy
    Commented May 17, 2014 at 12:30
  • @Nimbuz now it'l do the job for you. Commented May 17, 2014 at 12:30
3
if ( $('.panel').length >= 2 ) {
    console.log('exists')
}

This should work

3
  • oh yeah, I wrote this very quickly - still didn't get the cake! Thanks anyway, I won't edit the answer so people see what you meant.
    – Fonzy
    Commented May 17, 2014 at 13:09
  • 1
    @Fonzy Sorry, but some of the future referrers might not have patience to view the comments. Commented May 17, 2014 at 13:12
  • np mate, just learning how to get around here. TIL ;)
    – Fonzy
    Commented May 17, 2014 at 13:13
1

Simply use the the length property ;)

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.