How to get class name by using id in javascript
Asked Answered
N

5

6

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?

Nevsa answered 2/8, 2011 at 15:44 Comment(0)
F
16

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);
Fanciful answered 2/8, 2011 at 15:46 Comment(2)
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 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 run window.document.getElementById('slide-18415'), it returns [object HTMLLIElement]. any more ideas?Nevsa
What about if the li has more than one class?Etamine
M
6
document.getElementById('my-element-id').className
Maki answered 2/8, 2011 at 15:46 Comment(1)
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
L
2

The appropriate property is .className

EG: window.document.getElementById('my-element-id').className //returns "class-1 classes"

Lop answered 2/8, 2011 at 15:46 Comment(0)
D
2

You can use className.

document.getElementById('myelement').className
Dvina answered 2/8, 2011 at 15:47 Comment(0)
G
0

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')
Gainey answered 26/7, 2022 at 17:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.