Get class list for element with jQuery

后端 未结 17 1609
粉色の甜心
粉色の甜心 2020-11-22 03:20

Is there a way in jQuery to loop through or assign to an array all of the classes that are assigned to an element?

ex.

17条回答
  •  孤独总比滥情好
    2020-11-22 03:36

    I had a similar issue, for an element of type image. I needed to check whether the element was of a certain class. First I tried with:

    $('').hasClass("nameOfMyClass"); 
    

    but I got a nice "this function is not available for this element".

    Then I inspected my element on the DOM explorer and I saw a very nice attribute that I could use: className. It contained the names of all the classes of my element separated by blank spaces.

    $('img').className // it contains "class1 class2 class3"
    

    Once you get this, just split the string as usual.

    In my case this worked:

    var listOfClassesOfMyElement= $('img').className.split(" ");
    

    I am assuming this would work with other kinds of elements (besides img).

    Hope it helps.

提交回复
热议问题