James
James

Reputation: 2033

finding div id on click

Let's assume I have the following structure:

<div id="divid1">
  <div id="divid2">
    <div id="divid3">
    </div>
    <div id="divid4">
    </div>
  </div>
  <div id="divid5">
   </div>
</div>

The above code is merely an example to explain the problem so don't pay much attention to it.

Now let's assume I have the following jQuery:

$("#divid1").click(function(){});

Now.. What I want to do is the following:

Constraints:

Upvotes: 1

Views: 13125

Answers (3)

Calvin Froedge
Calvin Froedge

Reputation: 16373

$("#divid1 div").click(function(){ console.log(this.id);});

See full source of successful test:

<!doctype html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    $("#divid1 div").click(function(){ console.log(this.id);});
});
</script>
<style type="text/css" rel="stylesheet">
    div { display:block;height:20px;background:#000;}
</style>
</head>
<body>
<div id="divid1">
  <div id="divid2">
    <div id="divid3">
    </div>
    <div id="divid4">
    </div>
  </div>
  <div id="divid5">
   </div>
</div>

</body>
</html>

Upvotes: 2

zaoudis
zaoudis

Reputation: 120

$("#divid1").find().bind('click', function(){
    $(this).attr("id");
});

Upvotes: 0

Benjamin Crouzier
Benjamin Crouzier

Reputation: 41855

Try this:

$("#divid1 div").click(function(){
  alert($(this).attr("id"));
  return false; // avoid parents divs if you have nested divs
});

jsFiddle here

Upvotes: 5

Related Questions