JavaScript - get element's class

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
User avatar
Oren
DevNet Resident
Posts: 1640
Joined: Fri Apr 07, 2006 5:13 am
Location: Israel

JavaScript - get element's class

Post by Oren »

I really don't know JavaScript but I'm trying to edit some extension for Vanilla so I need some help, thanks in advance :wink:

Let's say that this is some part from my source:

Code: Select all

<li id="my_id" class="my_class">
Now, I have a JavaScript variable targetId which holds the name of the element's id. So: targetId = 'my_id'.
How can I get, let's say into another variable, the class of the element which its id is held by targetId?

Something like this:

Code: Select all

var my_class = some_made_up_function(targetId);
After the above line, my_class should hold the string 'my_class'.
User avatar
aaronhall
DevNet Resident
Posts: 1040
Joined: Tue Aug 13, 2002 5:10 pm
Location: Back in Phoenix, missing the microbrews
Contact:

Post by aaronhall »

Maybe this will work (not tested):

Code: Select all

className = document.getElementById('myElement').getAttribute('class')
User avatar
Oren
DevNet Resident
Posts: 1640
Joined: Fri Apr 07, 2006 5:13 am
Location: Israel

Post by Oren »

Oh, thank you so much aaronhall! :D
User avatar
n00b Saibot
DevNet Resident
Posts: 1452
Joined: Fri Dec 24, 2004 2:59 am
Location: Lucknow, UP, India
Contact:

Post by n00b Saibot »

Code: Select all

elemClass = document.getElementById('myElement').className
Post Reply