Javascript 如何通过在javascript中使用id来获取类名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6914751/
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
How to get class name by using id in javascript
提问by Josh Sherick
I have a HTML Element, or list item, which has both an idand a classassigned to it. I am writing automated tests, and I need to check the classfor this element. In the test, when I call window.document.getElementById('my-element-id'), it does return the correct element, but there is no classproperty on it. Is there another way to check the class?
我有一个 HTML 元素或列表项,它同时分配了 anid和 a class。我正在编写自动化测试,我需要检查class这个元素。在测试中,当我调用 时window.document.getElementById('my-element-id'),它确实返回了正确的元素,但它没有任何class属性。有没有另一种方法来检查class?
回答by Jamie Dixon
The property you're looking for is className.
您正在寻找的属性是className。
Here's a working example: http://jsfiddle.net/xxEtj/
这是一个工作示例:http: //jsfiddle.net/xxEtj/
HTML
HTML
<ul>
<li id="myId" class="myClass">Item one</li>
</ul>
JS
JS
var li = document.getElementById('myId');
alert(li.className);
回答by Jeremy Roman
document.getElementById('my-element-id').className
回答by Justin Long
The appropriate property is .className
适当的属性是 .className
EG: window.document.getElementById('my-element-id').className //returns "class-1 classes"
EG: window.document.getElementById('my-element-id').className //返回“class-1 classes”
回答by Joe
You can use className.
您可以使用className.
document.getElementById('myelement').className

