1

Is there a jQuery function similar to replaceWith() to replace an element with a new element, without destroying the original element (simply hiding it).

Randomblue
  • 112,777
  • 145
  • 353
  • 547

6 Answers6

1

Toggling visibility may work in some cases, but the preferred method would be to clone the original element. For example:

var clone = $('#elementOne');
$('#elementToBeReplaced').replaceWith(clone);

This is especially useful when managing form inputs as the DOM doesn't care if the element is visible or not.

png
  • 1,130
  • 14
  • 18
1

Use a combination of hide[API Ref] and after[API Ref]:

$('#oldElem').hide().after($('#newElem'));
FishBasketGordo
  • 22,904
  • 4
  • 58
  • 91
1

What about something like this?

$(this).before("this is what I'm inserting").hide();
Christian
  • 552
  • 1
  • 5
  • 12
1

you can do :

<button>replace</button>
<div class="toReplace">your first content</div >
<div class="toReplace" style="display: none">your second content</div >

then in js :

$("button").click(function () {
  $("toReplace").toggle();
});
tahir
  • 1,016
  • 1
  • 11
  • 21
0

Just insert the element after or before it and then hide the element itself. Try this

$("element").hide().after($("newElement"));
ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124
0

If you want to hide it with css just call .hide() before .after() like:

$('#theolddiv').hide().after('$(<div>The new div</div>'));

If you want to completely remove it from the DOM, not just hide it with css, but want to be able to re-insert it later, maybe somewhere else in the DOM even, then store it in a variable like:

var $x = $('#theolddiv');
$x.replaceWith('<div>The new div</div>');
// Do stuff here, you can put $x back in the DOM if you want.

That actually makes a copy of the Object, but it's good enough :)

Paul
  • 139,544
  • 27
  • 275
  • 264