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.
Might be better to break that up a bit, but you need to start with the element or find it. So you could either:
or
find and wrap
Edit: regarding OP edit
Keep in mind .add() (http://api.jquery.com/add/) already exists and does what the name implies. Also, something like
will ultimately make your code more manageable and readable
jQuery already has classifying methods to filter and traverse the dom. In your case of the DOM, you could easily use .find(‘span’) to get to the element – or .children(‘span’) – use of good selectors and overall site architecture is important here.
Also, the .end() function is pretty bad-ass: