开发者

Get the last classname of an array with jquery

开发者 https://www.devze.com 2023-01-26 20:44 出处:网络
i want get the last item of an array with class names. My code looks like this var getClassName = []; getClassName = $(this).attr(\'class\').split();

i want get the last item of an array with class names. My code looks like this

var getClassName = [];
getClassName = $(this).attr('class').split();
console.log(getClassName);

In the console i 开发者_开发知识库become get this answer

["classname1 classname2"]

how can i get the last class name?

Thanks


console.log(getClassName[getClassName.length-1]);

Will do, but you need to pass an argument to split():

var getClassName = $(this).attr('class').split(' ');
var lastIndex = getClassName.length - 1;
console.log(getClassName[lastIndex]);

EDIT: On using this.className
Consider using this.className instead of $(this).attr('class'). This is mentioned in other answers.

Andy E has done a great write-up on how we tend to overuse jQuery: Utilizing the awesome power of jQuery to access properties of an element. The article specifically treats the use of .attr("id") but the issue is the same for $(...).attr('className') vs. this.className.

You could even use

var getClassName = (this.className || '').split(' ');

if you're not sure that .className exists.


As jensgram points out, you're nearly there; see his answer for the detail if you want to stay jQuery-specific.

But you're making the browser do a lot of extra work, this is one of those times you really don't need jQuery:

var getClassName;
getClassName = this.className.split(' ');
console.log(getClassName[getClassName.length-1]);

The className property of DOM elements is supported by all major browsers (and probably all minor ones).

Still, unless you're doing this in a tight loop, the extra overhead of the $() and attr calls probably doesn't really matter much.


$(this).attr('class').split(' ').pop()


Note the documentation for split:

http://www.w3schools.com/jsref/jsref_split.asp

You need to write:

split(' ')

Without the separator "the entire string will be returned"

0

精彩评论

暂无评论...
验证码 换一张
取 消