jQuery - find last class on the element
Asked Answered
M

2

23

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

Our element:

 <div class="class-1 class-2 some-other-class"></div>

Normal approach with split will not work here, as we do not know the number of classes. Can we check the length of the .split(' ') ?

var i = $('div').prop('class');
var j = i.split(' ')[x];

Any suggestions much appreciated.

Moreland answered 29/6, 2012 at 8:17 Comment(2)
If you want to do in one line then i.split(' ')[i.split(' ').length - 1] will get you the last class.Sirree
Classes are essentially unordered entities. Personally, I wouldn't want to rely on javascript/jQuery delivering the "correct" result. If I needed to know the last class added to an element (or a set of elements) then I would keep track of it by other means.Diplomatics
C
54

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.

Caseate answered 29/6, 2012 at 8:23 Comment(0)
D
18
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.

Drachm answered 29/6, 2012 at 8:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.