2
var el = $(this); // it's a form

At some point:

el.replaceWith('<p>Loading...</p>');

Later:

el.replaceWith(output);

Apparently el doesn't exist anymore after the first replaceWith...

Can I keep somehow el, obviously with the new content ?

Alex
  • 66,732
  • 177
  • 439
  • 641

2 Answers2

3

The original el has been removed and replaced by replaceWith. Create a new reference, using the return value of replaceWith:

var el = $(this); // it's a form
el = el.replaceWith('<p>Loading...</p>');
              //`el.replaceWith()` returns the new element
el = el.replaceWith(output);

If you intended to replace the inner content with the new element, while keeping the form, use:

el.html(""); //Clear html
el.append('<p>Loading...</p>');
Rob W
  • 341,306
  • 83
  • 791
  • 678
  • thanks, I've found out that replaceAll does what I want: `el = $('

    loading...

    ').replaceAll(el);`
    – Alex Oct 28 '11 at 15:17
  • 1
    replaceWith seems to return the element that was REMOVED, not the new element, check: http://api.jquery.com/replaceWith/ – opensas Feb 08 '13 at 14:31
  • also check this question at SO http://stackoverflow.com/questions/892861/replacing-an-element-and-returning-the-new-one-in-jquery – opensas Feb 08 '13 at 14:42
1

jquery's replaceWith returns the replaced element, not the new one

http://api.jquery.com/replaceAll/

you should do something like this:

var el = $(this); // it's a form
var $p = $('<p>Loading...</p>');

el.replaceWith($p);

// now el is unhooked from the dom, that is el.parent() === []
// it is $p who is now hooked, check with $p.parent() === (some node)

//so you should reassing it
el = $p;

// later on

el.replaceWith(output); // but remenber, once again el is unhooked

also, make sure to check this question: https://stackoverflow.com/a/892915/47633

Community
  • 1
  • 1
opensas
  • 60,462
  • 79
  • 252
  • 386