replaceWith() bugs
replaceWith() bugs
I think the replaceWith method has some bugs. I have an application
that requires me to replace a DOM node by ID. I have jQuery events
tied to elements inside the node that I want to keep after replacing
the content. The current behavior of replaceWith() is different in IE,
Mozilla, Safari, most exhibiting weirdness.
Mozilla acts as I expect - replaces the node and keeps the events, no
problem.
In IE, the node will replace but I need to re-bind my events to the
new content.
Safari replaces the node, but I cannot access my new node by it's id,
and cannot re-bind any events at all.
I believe the root problem is that replaceWith removes the old node
after the new content is appended. This confuses the browsers because
you can have multiple ID's for a split second and it makes all manner
of strangeness.
I believe the fix is to first remove the node, and then to append the
new content. I pasted the fixed implementation below. In Safari, IE,
Mozilla, and Opera, this exhibits the correct behavior - the node is
replaced, and all the old jQuery events function as expected.
Unfortunately, the function is a little longer:
replaceWith: function( value ) {
return this.each( function () {
var e = $(this);
var p = e.parent();
var s = e.prev();
e.remove();
if (s[0])
s.after(value);
else
p.prepend(value);
});
},
... instead of
replaceWith: function( value ) {
return this.after( value ).remove();
},