简体   繁体   中英

How to dynamically check if an element has mulitple class using jquery or javascript

How do I know a DOM element has more than one class?

For instance, knowing that the element may have one or both of test and b classes, I would check if it both classes are present in the following manner:

if(jQuery(a).hasClass('test') && jQuery(a).hasClass('b'){  
    //Do  something`
}

But I need to cover the case whereby I don't know what classes may be present.

Here is a function which takes an element and a particular class to search for. What it does is iterates through all the classes that the element passed is a part of and if it finds a match for the search value, you can define behaviour in the if statement.

You can call it as follows doSomething('#element', 'error'));

function doSomething(elementid, classname)
{
    var classes = $(elementid).attr('class').split(/\s+/);
    $.each( classes, function(index, current){        
        if (current == classname) {
            //do something here
        }
    });

}

Assuming that the class names aren't known, you can try something like this:

DEMO

<div class="test b" id="foo"></div>

===========================================
var elem = document.getElementById('foo');
if (elem.className.match(/ /)) {
    alert('class names: '+elem.className)
}

There is at least one way to do that with jQuery, and here goes:

var numberOfClasses = jQuery(element).attr("class").trim().split(/\s+/).length;

if(numberOfClasses > 1){
    // do what Ayush wants
}

Using jQuery : If $(element).attr("class").indexOf(' ') is not -1 then there are more than one class.

function hasMultipleClasses(elem) {
   if(elem.attr("class").indexOf(' ')>-1) 
    return true;
   else return false;
}

DEMO

The following code works for me. Please check this.

// This code will returns all the based on the selector and split them based on empty seperator
var arr = jQuery(a).attr('class').split(' ');

//Removes all empty strings
arr = jQuery.grep(arr, function( a ) {

    return a !== '';

});

// This condition will be satisfied on if the selector contains multiple classes
if(arr.length > 1){

  //Code to execute

}

Using jquery to do that is a little bit powerfull don't you think?

You can do it using native Javascript, with something like that:

element.className.trim().split(/ /).length > 1

This looks like you want a collection of those selected classes and then just loop through, instead of dynamically creating the if statement.

var selectedClasses = [ "test", "b" ];

var hasAllClasses = CheckIfAllClassesAvailable(a, selectedClasses);


function CheckIfAllClassesAvailable(a, selectedClasses) {

    //loop through all the selected classes
    for(String s : selectedClasses)
    {
        //check if the class is not available
        if(!jQuery(a).hasClass(s))
        {
           return false;
        }
    }
    return true;
}

I don't know if this code works syntactly (please see this as pseudocode), but I think this is the way to go, you then just have to create the array with the selected categories dynamically, which you can do with a simple call to a webservice, think about it.

You can rewrite this to a shorter variant if you use some nice jQuery one liners, but I think this is more clear for now.

    jQuery('selector').click(function () { // The event trigger
 var finalClass = []; // array to store all the classes which has been triggered by the event
        var i=0;
        jQuery('.collaps-list li').each(function () {
            finalClass[i] = jQuery(this).attr('id');
            i++;
        });  
jQuery(selector).each(function () {
            var $flag =0;
            for(i=0;i<finalClass.length;i++){
                if (jQuery(this).find('a').hasClass(finalClass[i])) {
                    $flag=1;
                }
                else{
                    $flag=0;
                    break;
                }
            }
            if($flag==1){
                jQuery(this).find('img').removeClass('grayscale');
            }
});

This worked for me

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM