0

Here's the thing - a click event adds a bunch of elements on the page, and they all have the same id (is there something wrong here?).

I use a live function to assign click event to all of these elements:

$("#tag").live('click', function() { console.log($("#tag").html()); });

When I click on any of them, only the value of first element gets logged.

How can I let the click event know on which of this elements I actually click? Thanks a lot!

Update: using classes and $(this) is the way to go. Problem solved. Thanks griegs and John!

2 Answers 2

1

If the added elements really do all have the same ID, and not the same class, then this is a problem. You'll need to post the code that's adding the elements if you'd like help with that.

I can see from the code you posted that you're attaching the live method to the .tag class, but inside the function you're referring to an element with ID #tag instead. You might want to read up on the difference between classes and IDs.

Try this, to solve your problem:

$(".tag").live('click', function() { 
    console.log($(this).html()); 
});

Alternatively, you can do the following to get the clicked-on element:

$(".tag").live('click', function(event) { 
    console.log($(event.target).html()); 
});
1
  • 1
    I thought I'd be better off with classes and started to fix that. And then I had to go, so I just decided to post the question to see what response it would get. My bad. Commented Mar 25, 2011 at 1:15
1

try using $(this).val() or $(this).html()

edit

If you want to loop through all thr #tag elements then you can still use $(this) to check the clicked tag against the element you are looping through. If that makes sense.

btw: why do you have multiple elements with the same ID? That's kinda bad. A better way might be to have elements with common class names that you can reference and attach events to.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.