[jQuery] Binding events to newly added DOM elements

[jQuery] Binding events to newly added DOM elements

Mike, what you're seeing happens because the $().after() method clones the
node you pass it instead of inserting the node itself. You can see this in
the code for after():
after: function() {
var a = $.clean(arguments);
return this.each(function(){
for ( var i = a.length - 1; i >= 0; i-- )
this.parentNode.insertBefore(
a[i].cloneNode(true),
this.nextSibling );
});
},
All of the related methods such as $().append() do this as well.
John, I've been meaning to ask you about this myself. I believe the reason
for the cloneNode() is that these functions may be dealing with multiple
matching elements which this.each() iterates over. But in the code I've been
writing, I find myself more often using the various $() DOM methods when I
know I'm working with a single match, and I want to write code like Mike was
trying to write.
To take a simpler example, where I would like to write
"$(foo).append(newElement)" I instead end up writing
"$(foo).get(0).appendChild(newElement)". It would sure be handy to have a
better way to write code like this where I know I'm dealing with a single
match and do not want the node cloned.
-Mike























    • Topic Participants

    • mike