javascript jQuery - html 标签上的 hasClass

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

jQuery - hasClass on html tag

javascriptjqueryhtml

提问by user2316341

$(html).hasClass("class"), $(document).hasClass("class"), $(document.html).hasClass("class")None works. What selector should I use to get the class of the tag ? Also, how can I find a list of standard elements which I can select in jQuery ?

$(html).hasClass("class"), $(document).hasClass("class"),$(document.html).hasClass("class")无作用。我应该使用什么选择器来获取标签的类?另外,如何找到可以在 jQuery 中选择的标准元素列表?

回答by

Try this one:

试试这个:

$('html').hasClass("class");
  • [!]You forgot to type quotation around html.
  • [!]您忘记在 周围键入引号html

Here you can find all jQuery Selectors.

在这里您可以找到所有 jQuery 选择器。



Extra Information

额外的信息

The .hasClass()method will return boolean. You can access the class nameby getting the classattribute with .attr()method:

.hasClass()方法将返回boolean。您可以通过使用方法获取属性来访问类名class.attr()

<div class="a" id="example1"></div>
var c = $('#element').attr('class'); // (string) a

If your element has multiple classes, you can split the string to convert it to an array:

如果您的元素有多个类,您可以拆分字符串以将其转换为数组:

<div class="a b c" id="example2"></div>
var k = $('#example2').attr('class').split(/\s+/); // [a, b, c]

Here is the FIDDLE DEMO.

这是FIDDLE DEMO.

回答by dsgriffin

"What selector should I use to get the class of the tag?"

“我应该使用什么选择器来获取标签的类?”

The other answers use hasClass(), which returns a boolean not a class:

其他答案使用hasClass()它返回一个布尔值而不是一个类

$('html').attr('class');

回答by Mohammad Adil

<html class="someClass">
</html>

Do this -

做这个 -

$('html').hasClass('someClass');

回答by Sacha

Your DOM is structured like this, basically:

您的 DOM 结构如下,基本上:

- document
  - documentElement
    - head
    - body

You can either use jQuery's internal selector engine by writing $('html').hasClass('class')or you can target the HTML element yourself by writing $(document.documentElement).hasClass('class').

您可以通过编写使用 jQuery 的内部选择器引擎,$('html').hasClass('class')也可以通过编写$(document.documentElement).hasClass('class').

回答by user2361114

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 has only a class, you can try:

如果你只有一个类,你可以尝试:

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