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
JavaScript getting an elements class without any libraries
提问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?
<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>


![Javascript nodejs v10.3.0 的 gulp 任务问题:src\node_contextify.cc:629:断言 `args[1]->IsString()' 失败](/res/img/loading.gif)