jQuery .closest() method gets the first element matched.
Syntax and Description
.closest(selector[, context])
gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.
selector
is a string containing a selector
expression to match elements against.
context (optional)
is a DOM element within
which a matching element may be found.
Return value is the new jQuery object.
Get the first span element
The following code gets the first span element after clicking.
<html>
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){<!-- www. jav a2 s. c o m-->
$(document).bind("click", function (e) {
$(e.target).closest("span").text("java2s.com");
});
});
</script>
</head>
<body>
<body>
<div><span>span</span><span>span</span><span>span</span></div>
</body>
</html>