Bort
Bort

Reputation: 7618

Select elements which have any of the classes of another element

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?

Upvotes: 0

Views: 113

Answers (1)

user1106925
user1106925

Reputation:

$('#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.

Upvotes: 5

Related Questions