Cecil Theodore
Cecil Theodore

Reputation: 9939

Splitting classes & matching them against another DIV. JQuery

I have a div named box which contains three classes. I want to create a variable named relatedBoxes that stores the check boxes that share any of the same classes that box has.

I am splitting up the classes and storing them in the variable named splitClass.

I now just need the method to see whether :checkbox contains any of the classes saved within splitClass. I have tried by creating the variable relatedBoxes but this doesn't quite work.

The markup:

<div id="box" class="marker blue large">

The JavaScript:

var c = $('#box').attr('class');
var splitClass = c.split(' ');

var relatedBoxes = $(':checkbox').hasClass(splitClass);

Thanks a lot guys

Upvotes: 1

Views: 415

Answers (2)

user578895
user578895

Reputation:

hasClass expect a single class name, you're passing it an array right now. If you're trying to find all elements with marker, blue or large, something like:

var relatedBoxes = $( ':checkbox' ).filter( '.' + splitClass.join( ',.' ) );

Upvotes: 4

Felix Kling
Felix Kling

Reputation: 816404

You can use .filter() [docs] and iterate over the classes of the element:

var splitClass = $('#box').attr('class').split(' ');

var relatedBoxes = $('input[type="checkbox"]').filter(function() {
    for(var i = 0, len = splitClass.length; i < len; i++) {
        if($(this).hasClass(splitClass[i])) return true;
    }
    return false;
});

Upvotes: 0

Related Questions