views:

245

answers:

5

Hi,

I have a bunch of inputs like this

<input id="someId" type="button" class="SomeClass" onclick="determineClass(this.id, event)" />

From javascript I would like to get the class, it's different for each input.

function determineClass(id, e) {
    var elementClass = //Somehow get the class here
}

It can be using jQuery or just plain javascript... Does anyone know how to do this?

Thanks, Matt

A: 

[edit]

Ah crap... not what you meant...

$('#id').attr('class');

[/edit]

SeanJA
He is already using jQuery. There is no need to use another library.
SolutionYogi
I really misread that question didn't I
SeanJA
I thought he was looking for the class of a javascript object...
SeanJA
You know you can delete an answer if it's not applicable to the question.
tvanfosson
I edited it to the right answer
SeanJA
+6  A: 
alert($('#someId').attr('class'));

If your input has multiple classes, attr('class') returns a space-delimited list of classnames. You can get the last one as follows:

alert($('#someId').attr('class').split(' ').slice(-1));

See Attributes/attr

karim79
+1  A: 

You would use:

$('#someId').attr('class')

But beware that if it has multiple classes it will return a string of all of them, so you'll have to use indexOf or a regex to check for a specific class in that case.

Gabriel Hurley
Could also slide with $('#someId')[0].className.
David Andres
...or $('#someId:first').attr('class')
David Andres
@David Andres - $('#someId:first') implies multiple elements of the same ID, big no-no.
karim79
@karim79: A big no-no, yes. Not going to disagree on that point.
David Andres
+1  A: 

A bit simpler using plain ol' JavaScript:

function determineClass(id, e)
{
  var elem = document.getElementById(id);

  if(elem)
  {
    alert(elem.className);
  }
}
David Andres
A: 

Using plain ol' javascript, if you already have a variable/reference to the element, you can pull the class out using "element.className"

So, for your element "someId" above:

element = document.getElementById('someId');
if(element) elementClass = element.className

This gets a little more complicated if you have multiple classes assigned to the element -- you'd have to split what you find in the className property by a space in order to separate them -- but that's the basics.

That said, if you've got the chance, use jQuery. It generally makes this kind of thing easier.

Weston C