Basheer Kharoti
Basheer Kharoti

Reputation: 4302

Get the last className but not the one specified

I've googled for this issue but really didn't find any help regarding this.

I've div which has 3 classes. I want to get the last className but not the one I specify.

E.x third is last class in the div but I do not want that to be selected except in this case I want the second last one to be selected.

So far I've tried

 $('div:not(.third)').attr('class').split(' ').pop();//Throwing Type Error

$('div').attr('class').split(' ').pop().not(".third");//.not is not a function

I've made simple fiddle for that If any buddy could help me out.

Thanks

https://jsfiddle.net/h67zhLzL/

Upvotes: 1

Views: 93

Answers (3)

empiric
empiric

Reputation: 7878

If I get you right you want to get the last item of an array, except it has a value you specified before:

var classes = $("div").attr('class').split(' ');
classes.pop();
var index = classes.indexOf('third');
if(index > -1){        
    classes.splice(index, 1);
}
var lastclass = classes.pop();

Demo

Reference

.indexOf()

.splice()

Upvotes: 1

Vitaliy Terziev
Vitaliy Terziev

Reputation: 6681

If i understood correct, this is your solution.

$("button").on("click",function(){
    var arr = $("div").attr('class').split(' ');

    alert(arr[arr.length -2]); 
});

https://jsfiddle.net/g495r038/1/

Upvotes: 0

CodingIntrigue
CodingIntrigue

Reputation: 78535

pop() does remove the last element, but it also returns the element which was removed. You just need to access the original array:

$("button").on("mouseenter",function(){
    var arr = $("div").attr('class').split(' '); // Split the class into the array
    arr.pop(); // Remove the last element
    // Make sure we're left with at least one class
    if(arr.length) console.log(arr[arr.length-1]);  // Prints "second"
});

Working Example

Upvotes: 1

Related Questions