tags:

views:

53

answers:

3

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. :)

A: 

You can loop through all of them using

$(".button").each(function(index) { 
    alert("index: " + index + " id: " + $(this).attr("id")); 
});
moi_meme
I was unaware of the each function. This could prove to be useful, thanks moi!
mrtwidget
A: 

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

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

jmucchiello
As said in the comments above, he *doesn't know* the ID, so this approach doesn't work.
Nick Craver
This answer was written before he edited the question to make clear what he wanted.
jmucchiello
@jmucchiello - The [original question](http://stackoverflow.com/posts/3046758/revisions) still had: "The ID value is dynamically generated, therefore I do not know it", but alright :)
Nick Craver
Hey, he could be dynamically generating the javascript too. So he would "know" the id. It wasn't very clear. But I'm done with it now.
jmucchiello
+1  A: 
$(".button").click(function() { 
    alert($(this).attr("id"));
});
SilentGhost
Since the edit, I suppose this makes the most sense.
jmucchiello
Thank you for your time and kindness to my post Silent. Your answer is concise and much appreciated. I have been using yahoo answers for years and this is my first post here, and wow. I will definitely become a regular contributor.
mrtwidget