Javascript jQuery - 仅从元素获取第一个类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3203966/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:39:54  来源:igfitidea点击:

jQuery - get the first class only from a element

javascriptjqueryclass

提问by Alex

The element looks like this:

该元素如下所示:

<li class="blah active"> ... </li>

jQuery.attr('class')will return both classes. How can I get only the 1st class ('blah' in this case) with jQuery?

jQuery.attr('class')将返回两个类。我怎样才能用 jQuery 只获得第一类(在这种情况下是“废话”)?

回答by Sarfraz

You need to splitthat into an array:

你需要把split它变成一个数组:

console.log(jQuery('selector').attr('class').split(' ')[0]);

回答by gblazex

var first = jQuery.attr('class').split(" ")[0];

回答by Hymanotonye

You can use the following to get the first class only from an element:

您可以使用以下内容仅从元素获取第一个类:

var firstClass = jQuery('selector')[0].classList[0]