Friday, November 20, 2015

jQuery: How to select DOM elements with multiple classes, etc. using the intersection set operator

Today I needed a way to select items that had a combination of classes employing a simple intersection set operation.  I think it took entirely too long to find it, so I'm writing this blog post to provide easier access to this answer.  I couldn't even find it on w3schools.com's CSS Selector list or jQuery's Category Selectors page.
Thank you, Stack Overflow!  Here's the link so that credit goes to where credit is due: How can I select an element with multiple classes?

The Problem

I have a bunch of elements scattered all over the web page and I want only those that are decorated with classes PetAvailableToBeSelected and ItemIsSelected.  Let's assume that looking for ItemIsSelected isn't enough by itself--there are other lists out there that can also be selected and you only want selected pets.

The Example

HTML Snippet:
<ul>
  <li class="CityAvailableToBeSelected">Austin, TX</li>
  <li class="CityAvailableToBeSelected ItemIsSelected">Round Rock, TX</li>
  <li class="CityAvailableToBeSelected">Georgetown, TX</li>
  <li class="CityAvailableToBeSelected ItemIsSelected">San Antonio, TX</li>
</ul>
<ul>
  <li class="PetAvailableToBeSelected">Rocky, the pet rock</li>
  <li class="PetAvailableToBeSelected ItemIsSelected">Tripod, the not-so-lucky dog</li>
  <li class="PetAvailableToBeSelected">Mr. Shakes, the Chihuahua</li>
  <li class="PetAvailableToBeSelected ItemIsSelected">Mr. Meowgi, the Persian kitten</li>
</ul>



The Answer 

$(".PetAvailableToBeSelected.ItemIsSelected");



Also, in case you want to only select list items with that, you can do this:
$("li.PetAvailableToBeSelected.ItemIsSelected");

Which, in this example, gives you the same result.

Happy developing and God bless!

No comments:

Post a Comment