JavaScript 获取一个没有任何库的元素类

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

JavaScript getting an elements class without any libraries

javascriptclass

提问by Zugwalt

I would like to get the value of the classattribute for an element using JavaScript. However in this particular situation I don't have the luxury of library such as YUI, jQuery, etc. and need to stick to the basics.

我想使用 JavaScript 获取元素的class属性的值。然而,在这种特殊情况下,我没有像 YUI、jQuery 等这样的库的奢侈,需要坚持基础。

Specifically, I am looping over a table and want to check the class of the cell.

具体来说,我正在遍历一个表格并想检查单元格的类别。

I tried:

我试过:

var colClass = el.getAttribute('class');

var colClass = el.getAttribute('class');

and

var colClass = el.class;

But neither seems to be working. In the above example, elis set from cells array of a table, such as var el = document.getElementById('myTable').rows[y].cells[y];

但两者似乎都不起作用。在上面的例子中,el是从表格的单元格数组中设置的,例如var el = document.getElementById('myTable').rows[y].cells[y];

回答by Bang Dao

Maybe you should try this

也许你应该试试这个

var colClass = el.className

回答by Karel Petranek

This line that you posted should work:

您发布的这一行应该有效:

var colClass = el.getAttribute('class');

Could you post what error you get in the browser? Make sure that el is not null.

你能发布你在浏览器中遇到的错误吗?确保 el 不为空。

If you won't get that one to work, the attribute of the object is className, not class:

如果你不会让那个工作,对象的属性是 className,而不是 class

var colClass = el.className;

回答by Nikita Rybak

className?

className?

Element.className

元素.className

<html>
<body id="myid" class="mystyle">

<script>
var x=document.getElementsByTagName('body')[0];
document.write("Body CSS class: " + x.className);
document.write("<br>");
document.write("An alternate way: ");
document.write(document.getElementById('myid').className);
</script>

</body>
</html>

回答by Vladimir verleg

Remember:

记住:

If you get an error and className does not work this can be due to your element being a jQuery object.

如果出现错误并且 className 不起作用,这可能是因为您的元素是 jQuery 对象。

works not on jquery

不适用于 jquery

In the picture above you see that I canot use className on a jQuery object

在上图中,您可以看到我不能在 jQuery 对象上使用 className