views:

50

answers:

3

Given this HTML:

<button id="buttonId1" class="hello universe">
<button id="buttonId2" class="hello world">

What's the correct way to do something like this:

$("#buttonId1").click(function ()
{    
   alert($("#buttonId1").getClass());
}

I realize the getClass function does not exist in JQuery or Javascript. But I'm hoping there's some way to approximate it. I have a more complex real world problem that's difficult to boil down into a simple question but basically I think I need to somehow access the class of an element and then use that class string to perform an additional selection such as this:

$(("#buttonId1").getClass().filter("world")).hide();

Perhaps there are simpler ways of hiding the buttonId2 in the code I've given - that's not really the point, though. What I'm interested in is how to get at the class and then use that further. The only solution I've come up with so far is use a long branch of if/else statements checking all of the possible classes using the hasClass function. But it's a very inelegant solution.

EDIT: Responding to Paolo's answer, perhaps something like this will work to hide button2:

$(("#buttonId1").attr('class')[0].filter("world")).hide();
+2  A: 

I think if you try to explain what your ultimate purpose is I might be able to actually help you achieve your ultimate result in the best "jQuery way" - without that, however, all I can say is that:

$("#buttonId1").click(function() {    
   alert($(this).attr('class'));
});

Would alert 'hello' and:

$("#buttonId2").click(function() {    
   alert($(this).attr('class'));
});

Would alert 'hello world'

(As a side note, redoing the selector inside an event function like you have in your example is bad practice; you can simply use $(this) to signify the element that is currently being acted upon)

Paolo Bergantino
I want to use the class 'hello' which is shared by both buttons to hide button2. To do this I would also need to filter on the 'world' class which button2 has but button1 does not. Thanks for the tip about $(this).
fritz carlton
correct me if I'm wrong, but attr('class') will return an array, not a string... there are two classes listed: `["hello","world"]` So the next question is which one?
DGM
Yes, I would need to retrieve the first element of the attr('class') array and then apply that in the filter to the second element. Sounds kludgy, I know.
fritz carlton
I updated the question to give an indication of what I have in mind based on Paolo's feedback.
fritz carlton
No, DGM, it would not return an array. It returns a string.
Paolo Bergantino
+1  A: 

Try this:

$("#buttonId1").click(function ()
{
 var classname = $("#buttonId1").attr("class")
 alert(classname);
}
Marcos Buarque
A: 

Reference: element.className

$("#buttonId1").click(function ()
{    
    alert(document.getElementById("buttonId1").className);
}
Joe Chung