jQuery - find last class on the element

后端 未结 2 1061
醉酒成梦
醉酒成梦 2020-12-10 11:17

How to find last class on the element without knowing exact number of classes?

Our element:

 
&l
相关标签:
2条回答
  • 2020-12-10 11:31
    var classStr = $('div').attr('class'),
        lastClass = classStr.substr( classStr.lastIndexOf(' ') + 1);
    

    DEMO

    As classStr contains class names separated by a single space, so lastIndexOf(' ') will find the last space and make partition from there and give you the last class name.

    0 讨论(0)
  • 2020-12-10 11:45

    The simplest solution is to use pop, which accesses the last element in the array.

    var lastClass = $('div').attr('class').split(' ').pop();
    

    Note that pop also removes the element from the array, but since you aren't doing anything else with it, that's not a problem.

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