最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery - hasClass on html tag - Stack Overflow

programmeradmin1浏览0评论

$(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") 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 ?

Share Improve this question edited May 16, 2013 at 10:46 dsgriffin 68.6k17 gold badges140 silver badges138 bronze badges asked May 16, 2013 at 9:36 user2316341user2316341 3754 gold badges7 silver badges13 bronze badges
Add a comment  | 

5 Answers 5

Reset to default 6

Try this one:

$('html').hasClass("class");
  • [!] You forgot to type quotation around html.

Here you can find all jQuery Selectors.


Extra Information

The .hasClass() method will return boolean. You can access the class name by getting the class attribute with .attr() method:

<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.

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

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

$('html').attr('class');
<html class="someClass">
</html>

Do this -

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

Your DOM is structured like this, basically:

- 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').

If your <div> has an 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");
发布评论

评论列表(0)

  1. 暂无评论