Miguel Moura
Miguel Moura

Reputation: 39474

Find an element that has two CSS classes

I have the following DIV:

<div class="gallery home"></div>

And I have the Query:

  if ($('.gallery.home')) {
    console.log('home');
  }

  if ($('.gallery.showcase')) {
    console.log('showcase');
  }

The problem is that both if return true. Shouldn't only the first one return true?

I then tried using only Javascript the same happens:

  if (document.getElementsByClassName('.gallery.home')) {
    console.log('home');
  }

  if (document.getElementsByClassName('.gallery.showcase')) {
    console.log('showcase');
  }

How to match an element that has 2 classes?

Upvotes: 1

Views: 60

Answers (4)

Sergiu Paraschiv
Sergiu Paraschiv

Reputation: 10163

$('.gallery.showcase') returns a jQuery wrapped list of objects which is true-ish even if no elements matched.

$('.gallery.showcase').length > 0 would be what you need.

Upvotes: 5

hurricane
hurricane

Reputation: 6734

In the documentation it says;

You may also call getElementsByClassName() on any element; it will return only elements which are descendants of the specified root element with the given class names.

Also, you can see in the examples:

https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName

If you want to select a specific element you can use querySelector

if (document.querySelectorAll('.gallery.home')) {
  console.log('home');
}

if (document.querySelectorAll('.gallery.showcase')) {
  console.log('showcase');
}

For the jquery part $('') will always return an object.

Upvotes: 2

ankitkanojia
ankitkanojia

Reputation: 3122

You can compare it with a single or separate condition.

Single Condition Like

if($('.gallery.home').length > 0)
if($('.gallery.showcase').length > 0)

Separate Condition Like

if($('.gallery').length > 0 && $('.home').length > 0)

if($('.gallery').length > 0 && $('.showcase').length > 0)

console.log($('.gallery').length > 0 && $('.home').length > 0)

console.log($('.gallery').length > 0 && $('.showcase').length > 0)

console.log($('.gallery.home').length > 0)

console.log($('.gallery.showcase').length > 0)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="gallery home"></div>

Upvotes: 1

sidonaldson
sidonaldson

Reputation: 25314

document.getElementsByClassName('gallery showcase');

It's space-delimited and without the dot!

Upvotes: 2

Related Questions