Is there a jQuery function similar to replaceWith() to replace an element with a new element, without destroying the original element (simply hiding it).
            Asked
            
        
        
            Active
            
        
            Viewed 3,210 times
        
    1
            
            
        
        Randomblue
        
- 112,777
 - 145
 - 353
 - 547
 
- 
                    http://stackoverflow.com/questions/918792/use-jquery-to-change-an-html-tag – Chamika Sandamal Aug 24 '11 at 17:34
 
6 Answers
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
            
            
        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