jquery - how to check if element has any classes attached to it

后端 未结 8 1242
情深已故
情深已故 2021-01-27 02:20

you would imagine this would be easy to implement, but oh well..

anyway, I have an element to which classes are added or removed based of interaction on the site.

<
相关标签:
8条回答
  • 2021-01-27 02:53

    You have to check if class attribute:

    • Present but no class( class="")
    • Not present(undefined)

    .

    <div id="mydiv" class="">  // with class attribute but no class
    <div id="mydiv">   // even without class attribute so no class
    
    attr = $("#mydiv").attr("class")
    hasClass = (attr == undefined || attr.replace(/\s+/, '') == "" )
    
    0 讨论(0)
  • 2021-01-27 02:56

    You can do one thing take all class from the element then count the classes , try following code :-

    var myClass = $("#mydiv").attr("class");
    var myClassArray;
    var myClassCount;
    
    if (myClass != "")
    {
        myClassArray = myClass.split(" ");
        myClassCount = myClassArray.length();
    }
    else
    {
        myClassCount = 0;
    }
    
    console.log(myClassCount); // Number of class attached to that element
    

    It may help you.

    0 讨论(0)
提交回复
热议问题