1

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

12
  • 5
    Which one do you want to target? One at random, the third one, the first, the last? Other? Commented Jun 15, 2010 at 15:44
  • 1
    Another note, you should prefix your IDs unless you're using an HTML5 doctype, IDs cannot start with a number in HTML 4. Commented Jun 15, 2010 at 15:47
  • 1
    FYI numerical id attributes aren't valid. The id must start with a letter. w3.org/TR/html401/types.html#type-name Commented Jun 15, 2010 at 15:47
  • @Nick - which one? id's are supposed to be unique on a page. Commented Jun 15, 2010 at 15:51
  • @jmucchiello - Which .button element Commented Jun 15, 2010 at 15:55

3 Answers 3

1
$(".button").click(function() { 
    alert($(this).attr("id"));
});
Sign up to request clarification or add additional context in comments.

1 Comment

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.
0

You can loop through all of them using

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

1 Comment

I was unaware of the each function. This could prove to be useful, thanks moi!
0

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

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

4 Comments

As said in the comments above, he doesn't know the ID, so this approach doesn't work.
This answer was written before he edited the question to make clear what he wanted.
The original question still had: "The ID value is dynamically generated, therefore I do not know it", but alright :)
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.