Reputation: 57
How to get class id of a button in jquery? I am trying with this code.
<div><button id="Button2" class="Default">2. Click to get Class ID.</button> </div>
Thanks in advance!
Upvotes: 2
Views: 21520
Reputation: 17651
$("#myButton").click( function() {
var class = $(this).attr("class");
});
Note that this can potentially contain multiple classes though.
If you need to check if a specific class exists in the CSS class list:
$("#myButton").click( function() {
var isHighlighted = $(this).hasClass("highlight");
});
There's also addClass() and removeClass(). Generally there should be very little reason to ever retrieve the full class attribute as a string - it's much easier to manipulate or compare the attribute by using the jQuery methods instead.
Upvotes: 6
Reputation: 74738
If you want to get all the ids of the clicked button then just capture the target's id of the clicked event:
see this in the fiddle: http://jsfiddle.net/DhjBW/
this the html:
<span></span>
<button id='button 1'>btn1</button>
<button id='button 2'>btn2</button>
<button id='button 3'>btn3</button>
this the jQuery:
$("button").click(function(e) {
$('span').text($(e.target).attr("id"));
});
Upvotes: 0
Reputation: 148110
You need to bind click
event to button first and then use jQuery attr()
to get the class.
$('#Button2').click(function(){
alert($(this).attr('class'));
})
Upvotes: 1
Reputation: 2220
<input type="button" id="btn1" class="btnclass" onclick="alert(this.className);" />
or
document.getElementById('btn1').onclick = function () { alert(this.className); }
The second option is the better way to do things.
Upvotes: 1