Skip to main content

Bug Tracker

Side navigation

#2697 closed bug (fixed)

Opened April 16, 2008 05:22PM UTC

Closed December 05, 2009 08:31PM UTC

replaceWith should remove before adding

Reported by: scottgonzalez Owned by: flesler
Priority: major Milestone: 1.4
Component: core Version: 1.4a1
Keywords: replaceWith Cc:
Blocked by: Blocking:

See Google Group post for description and possible fix.

Attachments (0)
Change History (3)

Changed May 07, 2008 05:52PM UTC by flesler comment:1

owner: → flesler
status: newassigned

Changed April 21, 2009 07:10PM UTC by snaury comment:2

I'm surprised that this bug wasn't fixed for a whole year, and I've just been affected by this.

The posting in Google Groups asks for a concrete example, and I have one. I'm creating a Rails application, where I have a _commentform template, that contains a form element, that is submitted with ajax. If there are errors in any fields, then _commentform is rerendered with error messages, and $('#formid').replaceWith('...commentform...') is used to replace old form with the new one.

Later I've added a script tag in that form, that performs some javascript on buttons on the form, using $('#buttonid'). But, unfortunately, when using .replaceWith, scripts are executed when there are *two* elements on the page with the same id, and because old form elements are before new form elements, jQuery picks old buttons (which are later removed), and now I have buttons that don't do what I'd expect.

Needless to say, that Prototype handles this situation correctly, and old elements are removed before new ones are injected, so everything works very well.

Also, I've studied jQuery sources, and it seems that using prev/after/prepend has to do a little more work than next/before/append, so perhaps this implementation would be better than the previous one:

$.fn.replaceWith = function(value) {
  return this.each(function() {
    var e = $(this);
    var s =;
    var p = e.parent();
    if (s.size())

Changed December 05, 2009 08:31PM UTC by john comment:3

resolution: → fixed
status: assignedclosed