blueintegral
blueintegral

Reputation: 1271

Detect a click on DIVs with unpredictable IDs in jQuery

I have several div tags and I'm trying to detect which one clicked. Each result has a unique title, but the same id. How do I use .click() to know which one was clicked so I can get it's ID and use it?

Upvotes: 1

Views: 209

Answers (4)

Ishan Jain
Ishan Jain

Reputation: 8171

Try this -

$('div').click(function(e){
    e.stopPropagation();
    alert("Id: " + event.toElement.id);
    alert("Title: " + event.toElement.title)
});

Try This

Upvotes: 0

Mrchief
Mrchief

Reputation: 76218

This one checks if the div has img as a child and then triggers the click.

$('div:has(img)').click(function(){
    // do something
});

Upvotes: 1

Jorge Guberte
Jorge Guberte

Reputation: 11054

You can add a listener that captures clicks using the parent > child methods. For instance:

<div id="parent">
   <div id="result" title="df45fds46"></div>
   <div id="result" title="48df6sfsd"></div>
</div>

Then on the javascript:

$("#parent div").click(function(){
   console.log(this.attr('title')); // or $(this).attr('title'), i'm not quite sure
});

Upvotes: 0

SeanCannon
SeanCannon

Reputation: 77966

$('div').click(function(){
    alert(this.id);
});

Upvotes: 4

Related Questions