Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - find last class on the element

Tags:

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.

like image 459
Iladarsda Avatar asked Jun 29 '12 08:06

Iladarsda


People also ask

How to get last element of class jQuery?

jQuery last() Method The last() method returns the last element of the selected elements. Tip: To return the first element, use the first() method.

How to select last div in jQuery?

The :last selector selects the last element. Note: This selector can only select one single element. Use the :last-child selector to select more than one element (one for each parent). This is mostly used together with another selector to select the last element in a group (like in the example above).

Is last child jQuery?

It is a jQuery Selector used to select every element that is the last child of its parent. Return Value: It selects and returns the last child element of its parent.


2 Answers

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.

like image 172
lonesomeday Avatar answered Sep 30 '22 08:09

lonesomeday


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.

like image 23
thecodeparadox Avatar answered Sep 30 '22 09:09

thecodeparadox