How to find last class on the element without knowing exact number of classes?
Our element:
&l
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.
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.