qadenza
qadenza

Reputation: 9293

how to get the last class of a div

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>

Upvotes: 2

Views: 562

Answers (4)

ambianBeing
ambianBeing

Reputation: 3529

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>

Upvotes: 0

D A
D A

Reputation: 2054

"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.

Upvotes: 0

fdomn-m
fdomn-m

Reputation: 28611

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>

Upvotes: 0

Always Helping
Always Helping

Reputation: 14570

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>

Upvotes: 3

Related Questions