Reputation: 4302
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
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();
Reference
Upvotes: 1
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
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"
});
Upvotes: 1