Javascript 使用 jQuery 获取类名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2400386/
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 00:07:56  来源:igfitidea点击:

Get class name using jQuery

javascriptjquery

提问by X10nD

I want to get the class name using jQuery

我想使用 jQuery 获取类名

And if it has an id

如果它有一个 id

<div class="myclass"></div>

回答by Boldewyn

After getting the element as jQuery object via other means than its class, then

通过类以外的其他方式将元素作为 jQuery 对象获取后,然后

var className = $('#sidebar div:eq(14)').attr('class');

should do the trick. For the ID use .attr('id').

应该做的伎俩。对于 ID 使用.attr('id').

If you are inside an event handler or other jQuery method, where the element is the pure DOM node without wrapper, you can use:

如果您在事件处理程序或其他 jQuery 方法中,其中元素是没有包装器的纯 DOM 节点,您可以使用:

this.className // for classes, and
this.id // for IDs

Both are standard DOM methods and well supported in all browsers.

两者都是标准的 DOM 方法,并且在所有浏览器中都得到很好的支持。

回答by sandino

It is better to use .hasClass()when you want to check if an element has a particular class. This is because when an element has multiple classit is not trivial to check.

最好是使用.hasClass()时要检查元素是否具有特定class。这是因为当一个元素有多个class时,检查起来并不容易。

Example:

例子:

<div id='test' class='main divhover'></div>

Where:

在哪里:

$('#test').attr('class');        // returns `main divhover`.

With .hasClass()we can test if the divhas the class divhover.

有了.hasClass()我们可以测试是否div有 class divhover

$('#test').hasClass('divhover'); // returns true
$('#test').hasClass('main');     // returns true

回答by Abdennour TOUMI

Be Careful , Perhaps , you have a class and a subclass .

小心,也许,你有一个类和一个子类。

  <div id='id' class='myclass mysubclass' >dfdfdfsdfds</div>

If you use previous solutions , you will have :

如果您使用以前的解决方案,您将拥有:

myclass mysubclass

So if you want to have the class selector, do the following :

因此,如果您想拥有类选择器,请执行以下操作:

var className = '.'+$('#id').attr('class').split(' ').join('.')

and you will have

你会有

.myclass.mysubclass

Now if you want to select all elements that have the same class such as div above :

现在,如果要选择具有相同类的所有元素,例如上面的 div :

   var brothers=$('.'+$('#id').attr('class').split(' ').join('.'))

that means

这意味着

var brothers=$('.myclass.mysubclass')

Update 2018

2018 年更新

OR can be implemented with vanilla javascript in 2 lines:

OR 可以在 2 行中使用 vanilla javascript 实现:

  const { classList } = document.querySelector('#id');
  document.querySelectorAll(`.${Array.from(classList).join('.')}`);

回答by Sankar

This is to get the second class into multiple classes using into a element

这是使用 into 元素将第二个类放入多个类中

var class_name = $('#videobuttonChange').attr('class').split(' ')[1];

回答by Madura Harshana

you can simply use,

你可以简单地使用,

var className = $('#id').attr('class');

var className = $('#id').attr('class');

回答by mg1075

If your <div>has an id:

如果您<div>id

?<div id="test" class="my-custom-class"></div>????????????????????????????????????????????????????????????????????????

...you can try:

...你可以试试:

var yourClass = $("#test").prop("class");


If your <div>has only a class, you can try:

如果您<div>只有一个class,您可以尝试:

var yourClass = $(".my-custom-class").prop("class");

回答by Paul Leclercq

To complete Whitestock answer (which is the best I found) I did :

为了完成 Whitestock 的回答(这是我找到的最好的答案),我做了:

className = $(this).attr('class').match(/[\d\w-_]+/g);
className = '.' + className.join(' .');

So for " myclass1 myclass2 "the result will be '.myclass1 .myclass2'

所以对于“myclass1 myclass2”,结果将是“.myclass1 .myclass2”

回答by Whitestock

If you're going to use the split function to extract the class names, then you're going to have to compensate for potential formatting variations that could produce unexpected results. For example:

如果您打算使用 split 函数来提取类名,那么您将不得不补偿可能产生意外结果的潜在格式变化。例如:

" myclass1  myclass2 ".split(' ').join(".")

produces

产生

".myclass1..myclass2."

I think you're better off using a regular expression to match on set of allowable characters for class names. For example:

我认为您最好使用正则表达式来匹配类名的一组允许字符。例如:

" myclass1  myclass2  ".match(/[\d\w-_]+/g);

produces

产生

["myclass1", "myclass2"]

The regular expression is probably not complete, but hopefully you understand my point. This approach mitigates the possibility of poor formatting.

正则表达式可能不完整,但希望你明白我的意思。这种方法减少了格式错误的可能性。

回答by Bilal Iqbal

<div id="elem" class="className"></div>

With Javascript

使用 JavaScript

document.getElementById('elem').className;

With jQuery

使用 jQuery

$('#elem').attr('class');

OR

或者

$('#elem').get(0).className;

回答by Sadikhasan

You can get class Name by two ways :

您可以通过两种方式获取类名称:

var className = $('.myclass').attr('class');

OR

或者

var className = $('.myclass').prop('class');