mrtwidget
mrtwidget

Reputation: 83

How do I select a class element based on its id in jQuery?

I have multiple dynamically generated buttons with a class name of ".button". Each of these are given an unknown ID value used to uniquely identify them. In jQuery I must select one and alert the values.

<div class="button" id="3"></div>

The ID value is dynamically generated, therefore I do not know it. I'm new to jQuery but am basically looking for something like this:

$(".button").attr("id").val();

How do I target one button when there are many? Thanks!

EDIT: I want to select whichever one the user clicks. The button in this case is a comment button. There is one for each "post". And I will change the ID to begin with a letter, as I am not using HTML5, whops. :)

Upvotes: 1

Views: 109

Answers (3)

jmucchiello
jmucchiello

Reputation: 18984

I would guess $('#id') is sufficient.

I prefer the Mootools method: $('id') as $ is just an alias for getElementById

Upvotes: 0

SilentGhost
SilentGhost

Reputation: 320009

$(".button").click(function() { 
    alert($(this).attr("id"));
});

Upvotes: 1

moi_meme
moi_meme

Reputation: 9328

You can loop through all of them using

$(".button").each(function(index) { 
    alert("index: " + index + " id: " + $(this).attr("id")); 
});

Upvotes: 0

Related Questions