开发者

replaceWith() without deleting the original element

Is there a jQuery function similar to replaceWith() to rep开发者_StackOverflow中文版lace an element with a new element, without destroying the original element (simply hiding it).


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();
});


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

$('#oldElem').hide().after($('#newElem'));


What about something like this?

$(this).before("this is what I'm inserting").hide();


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.


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

$("element").hide().after($("newElement"));


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 :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜