If you use append() to insert a new DOM node, is it possible to move the chain context to the new element?
This sample code illustrates the subject:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title></title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
</script>
<script type="text/javascript"><!--
$(function(){
$("<div></div>")
.appendTo("body")
.append("<span>Click me</span>")
.click(function(){
alert("Clicked on <" + this.tagName + ">, <SPAN> expected");
});
});
//--></script>
</head>
<body>
</body>
</html>
This code attachs an onclick handler to the <div>, but I want it in the new <span>.
Edit: clarification
I suppose I was thinking about a direct function such as add() or andSelf() that doesn't break the chain flow so much <:-)
Edit: solution summary
For the records: there doesn't seem to be a native findAppended() function. These are some of the alternatives:
Alter creation flow:
$("<span>Click me</span>")
.appendTo("body")
.wrap("<div></div>")
.click(function(){
alert("Clicked on <" + this.tagName + ">, <SPAN> expected");
});
Store the new element in a variable:
var span = $("<span>Click me</span>")
.click(function(){
alert("Clicked on <" + this.tagName + ">, <SPAN> expected");
});
$("<div></div>")
.appendTo("body")
.append(span);
Start a new subchain:
$("<div></div>")
.appendTo("body")
.append(
$("<span>Click me</span>")
.click(function(){
alert("Clicked on <" + this.tagName + ">, <SPAN> expected");
})
);
Find the new element after creating it:
$("<div></div>")
.appendTo("body")
.append("<span>Click me</span>")
.find("span:last")
.click(function(){
alert("Clicked on <" + this.tagName + ">, <SPAN> expected");
})
.end(); // Not necessary here, used to illustrate how to continue the chain
Note: code not tested.