开发者

replaceWith() without deleting the original element

开发者 https://www.devze.com 2023-03-30 17:41 出处:网络
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 :

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

精彩评论

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