Javascript 如何获取html元素的类标签

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

How to get html element's class tags

javascriptjqueryhtmlcssmodernizr

提问by Steven Lu

I'm using a custom modernizer config which has selected the features I employ in my page (and only those features).

我正在使用自定义的 Modernizer 配置,该配置选择了我在页面中使用的功能(并且仅选择了这些功能)。

So, I'd like to simply grab the className of the <html>of the page so I can check to see how many no-prefixed classes are present (maybe checking classlist.match(/no-/g).length) and determine if my javascript should just give up.

所以,我想简单地获取<html>页面的 className以便我可以检查有多少no-前缀类存在(可能检查classlist.match(/no-/g).length)并确定我的 javascript 是否应该放弃。

It's not clear whether I should use

不清楚我是否应该使用

document.getElementsByTagName('html').className

or

或者

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

or

或者

document.documentElement.className

回答by ZER0

I will go for:

我会去:

document.documentElement.className;

Because doesn't involve any function's call, neither an additional layer like jquery. Ideally this one is the cleanest and the fastest.

因为不涉及任何函数的调用,也没有像jquery这样的附加层。理想情况下,这是最干净和最快的。

回答by undefined

you can use jQuery hasClass` method:

你可以使用jQuery`hasClass方法:

Determine whether any of the matched elements are assigned the given class.

确定是否有任何匹配的元素被分配给给定的类。

if ( $('html').hasClass('no-something')) {
  // do something here
}

回答by Martin

If using plain JS, the equivalent would be:

如果使用普通 JS,则等效为:

document.getElementsByTagName('html')[0].className

回答by Besnik

If you are using jquery in your project why to not use this one:

如果您在项目中使用 jquery,为什么不使用这个:

var classList = $("html").attr('class').split(/\s+/);
var prefix = 'no-';

$.each( classList, function(index, item){
  if (item.substring(0, 2) === prefix) {
    //do something
  }
});

?

?

回答by Community Ans

 var allClasses = [];
 var allElements = document.querySelectorAll('*');

 for (var i = 0; i < allElements.length; i++) {
     if (allElements[i].hasAttribute("class")) {
        var classes = allElements[i].className.toString().split(/\s+/);
        for (var j = 0; j < classes.length; j++) {
             var cls = classes[j];
             if (cls && allClasses.indexOf(cls) === -1)
                allClasses.push(cls);
        }
     }
 }

 console.log(allClasses);