Reputation: 2395
Upon pressing a button , I would like to find the closest div to it. In the following code, when I press the "myButton" button, closest returns the div with id="outerDiv" where I'm interested in finding the div with id="innerDiv".
As far as I understand both divs are parents of the button so I don't quite understand what am I doing wrong.
Here is my code:
<html>
<head>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js'></script>
<script src='http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js'></script>
<script>
$(function()
{
$(".buttons").click(function(e){
alert(e.target.id)
alert($(e.target).closest("div").attr("id"))
});
});
</script>
</head>
<body>
<div id="outerDiv">
<table id="positions">
<div id="innerDiv">
<tr>
<th>name</th>
<th>id</th>
<th>button</th>
</tr>
<tr>
<td>omer</td>
<td>123</td>
<td><button id="myButton" class="buttons">Click</button></td>
</tr>
</div>
</table>
</div>
</body>
</html>
Upvotes: 2
Views: 9972
Reputation: 606
Your js code is working, just make validation to your html code by moving
<table id="positions">
and
</table>
into div.
Upvotes: 0
Reputation: 74738
You can make your structure like this (although you can make it as per your needs) its just a demo:
<div id="outerDiv">
<table id="positions">
<tr>
<td>
<div id='innerDiv1'>
<table>
<tr>
<th>name</th>
<th>id</th>
<th>button</th>
</tr>
<tr>
<td>omer</td>
<td>123</td>
<td><button id='myButton1' class="buttons">Click</button></td>
</tr>
</table>
</div>
</td>
</tr>
<tr>
<td>
<div id='innerDiv2'>
<table>
<tr>
<th>name</th>
<th>id</th>
<th>button</th>
</tr>
<tr>
<td>omer</td>
<td>123</td>
<td><button id='myButton2' class="buttons">Click</button></td>
</tr>
</table>
</div>
</td>
</tr>
</table>
you can test it out here: http://jsfiddle.net/yH4YH/1/
Upvotes: 1
Reputation: 902
Placing div inside table tag is not proper.If you need div with id 'innerDiv' try it
$(function () {
$(".buttons").click(function (e) {
//alert(e.target.id)
alert($(e.target).closest("table").find('div').attr("id"))
});
});
Upvotes: 1
Reputation: 2034
<html>
<head>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js'></script>
<script src='http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js'></script>
<script>
$(function()
{
$(".buttons").click(function(e){
alert(e.target.id)
alert($(e.target).closest("div").attr("id"))
});
});
</script>
</head>
<body>
<div id="outerDiv">
</div>
<div id="innerDiv">
<table id="positions">
<tr>
<th>name</th>
<th>id</th>
<th>button</th>
</tr>
<tr>
<td>omer</td>
<td>123</td>
<td><button id="myButton" class="buttons">Click</button></td>
</tr>
</table>
</div>
</body>
</html>
Upvotes: 0