使用jQuery获取类名

浦思源
2023-12-01

本文翻译自:Get class name using jQuery

I want to get the class name using jQuery 我想使用jQuery获取类名

And if it has an id 如果它有id

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

#1楼

参考:https://stackoom.com/question/A4Ru/使用jQuery获取类名


#2楼

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");

#3楼

你可以简单地使用,

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


#4楼

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('.')}`);

#5楼

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. 如果您要使用split函数来提取类名,那么您将不得不补偿可能产生意外结果的潜在格式变化。 For example: 例如:

" 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. 这种方法减少了格式不良的可能性。


#6楼

这是为了将第二个类用于元素中的多个类

var class_name = $('#videobuttonChange').attr('class').split(' ')[1];
 类似资料: