0

Given an element like

<div class="A B"></div>

where the classes of the div are unknown and/or can change, I want to select elements like

<div class="A"></div>
<div class="B"></div>
<div class="A B"></div>
<div class="B Foo"></div>

in other words any element which has class A or B.

jQuery has the is() function, so I thought about grabbing the string containing the classes of the main div using attr("class"), prefixing each class with . and using is() to filter, but that feels like a hack. Any way to do this elegantly?

Bort
  • 7,398
  • 3
  • 33
  • 48

1 Answers1

5
$('#targeted_div').click(function() {
    if (this.className) {
        var classes = $.trim(this.className).split(/\s+/);
        var matches = $('.' + classes.join(',.'));
    }
});

So if the classes for '#targeted_div' are A B, the selector for the matches will be '.A,.B'. In other words, it will select any elements that have at least one of those classes.

  • Probably want to use `/\s+/`, http://stackoverflow.com/questions/1227286/get-class-list-for-element-with-jquery – Erik Philips Apr 17 '12 at 18:09
  • This is basically what I was thinking, though I had thought `is()` would act as a selector but its just a true/false test. Looks good – Bort Apr 17 '12 at 18:09