how to get the last class of a div

Viewed 94

in the example below the last class of a div is tex1 and I need it in console
something like this:

let last = $('#tex').attr('class').last();
console.log(last);  // error
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='tex' class='tex texonly tex1'>lorem</div>

4 Answers

You need to use .split and .pop() to get the last class from your element.

.last() is used for doing something on the last element in the your parent div or etc

Run snippet below to see it working.

let last = $('#tex').attr('class').split(' ').pop();
console.log(last); // error
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<div id='tex' class='tex texonly tex1'>lorem</div>

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

var lastClass = $('#tex').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."

This answer was provided here for a similar question.

With vanilla JS you could use classList and get the last class by length.

const classes = document.getElementById("tex").classList;
console.log(classes[classes.length-1]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='tex' class='tex texonly tex1'>lorem</div>

You can use javascript's .classList to get an array-like list (then convert to a "real" array). A polyfill will give you array.last().

if (!Array.prototype.last){
    Array.prototype.last = function(){
        return this[this.length - 1];
    };
};

let last = [...$('#tex')[0].classList].last();
console.log(last);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='tex' class='tex texonly tex1'>lorem</div>

Related