February 6th, 2010
I was reading a blog post about jQuery event delegation by Karl Swedberg yesterday. One corner case I found in his examples is dealing with nested DOM elements of the same type (e.g. divs within divs, or in the following example tables within tables).
Here’s a solution (albeit possibly not the best) that makes use of jQuery’s parentsUntil() method, added in version 1.4:
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
”http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en-us” lang=”en-us”
xmlns:v=”urn:schemas-microsoft-com:vml”>
<head profile=”http://www.w3.org/2005/10/profile”>
<script type=”text/javascript”>
$(function() {
$(“#outer”).click(function(event) {
var parentCells = $(event.target).parentsUntil(this).filter(“td”);
var outermostCell = $.merge($(event.target), parentCells).last();
$(“#output”).text(outermostCell.text());
});
});
</script>
</head>
<body>
<div id=”output”>[Nothing clicked]</div>
<br />
<table id=”outer” border=”1″ cellpadding=”15″>
<tr>
<td>a</td>
<td>b</td>
<td>c</td>
</tr>
<tr>
<td>d</td>
<td>
<table id=”inner” border=”1″ cellpadding=”15″>
<tr>
<td>i</td>
<td>ii</td>
<td>iii</td>
</tr>
<tr>
<td>iv</td>
<td>v</td>
<td>vi</td>
</tr>
<tr>
<td>vii</td>
<td>viii</td>
<td>ix</td>
</tr>
</table>
</td>
<td>e</td>
</tr>
<tr>
<td>f</td>
<td>g</td>
<td>h</td>
</tr>
</table>
</body>
</html>