I have a HTML Element, or list item, which has both an id
and a class
assigned to it. I am writing automated tests, and I need to check the class
for this element. In the test, when I call window.document.getElementById('my-element-id')
, it does return the correct element, but there is no class
property on it. Is there another way to check the class
?
How to get class name by using id in javascript
Asked Answered
The property you're looking for is className
.
Here's a working example: http://jsfiddle.net/xxEtj/
HTML
<ul>
<li id="myId" class="myClass">Item one</li>
</ul>
JS
var li = document.getElementById('myId');
alert(li.className);
What about if the
li
has more than one class? –
Etamine document.getElementById('my-element-id').className
Hi, thanks for the prompt answer. I have
<li id="slide-18415" class="zoom-out">
. Are you saying that if I call the code that you have above (changing the variable names), it will return "zoom-out"? If so, I don't think it is working for me for some reason. I am actually running these commands in PHP, but they go through selenium (helps with test automation) which runs them in the browser and returns the stuff. But I think that is working properly, because when I run window.document.getElementById('slide-18415')
, it returns [object HTMLLIElement]. any more ideas? –
Nevsa The appropriate property is .className
EG: window.document.getElementById('my-element-id').className //returns "class-1 classes"
You can use className
.
document.getElementById('myelement').className
If you're using document.getElementById('my-element-id').className
, somehow it will not always return the classes string. This happened when I get a SVG element by using document.getElementById
.
So, my recommendation would be using the .getAttribute()
:
document.getElementById('my-element-id').getAttribute('class')
© 2022 - 2024 — McMap. All rights reserved.
<li id="slide-18415" class="zoom-out">
. Are you saying that if I call the code that you have above (changing the variable names), it will display an alert that says "zoom-out"? If so, I don't think it is working for me for some reason. I am actually running these commands in PHP, but they go through selenium (helps with test automation) which runs them in the browser and returns the stuff. But I think that is working properly, because when I runwindow.document.getElementById('slide-18415')
, it returns [object HTMLLIElement]. any more ideas? – Nevsa