fritz carlton
fritz carlton

Reputation: 71

How do you retrieve the class to hide the button?

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();

Upvotes: 1

Views: 272

Answers (3)

Joe Chung
Joe Chung

Reputation: 12123

Reference: element.className

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

Upvotes: 0

Marcos Buarque
Marcos Buarque

Reputation: 3418

Try this:

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

Upvotes: 1

Paolo Bergantino
Paolo Bergantino

Reputation: 488464

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)

Upvotes: 2

Related Questions