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 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') } 
Sign up to request clarification or add additional context in comments.

2 Comments

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
@Nimbuz now it'l do the job for you.
3
if ( $('.panel').length >= 2 ) { console.log('exists') } 

This should work

3 Comments

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 Sorry, but some of the future referrers might not have patience to view the comments.
np mate, just learning how to get around here. TIL ;)
1

Simply use the the length property ;)

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.