If I overwrite html, is it removed from dom?
Suppose I have the following code:
... <div id="div1"> <div id="div2">Original div2</div> </div> <div id="div3"></div> ... if i run
$('#div1').html(''); $('#div3').html('<div id="div2">New div2</div>'); Am I having problems because I did not use .remove () to remove # div2 from dom, or did html cleanup do this for me?
What if div2 contains some javascript that attaches the handler, say something like
$('#div2').on('click',function() { ... }); will also be deleted, or do I need to disable () it?
You should use $('#div1').empty(); instead of using $('#div1').html('') you can clone an element using $('#div3').html($('#div2').clone(true)); // this carries any data events associated with it.
If you move items to another container or another position, you can simply use append, prepend, before , after . All your data and events will be intact.
See the following: -
<div id="container1">Container <div id="div2">div2</div> </div> <div id="container2">cotainer2</div> $('#div2').click(function () { alert('test') }); $('#container2').append($('#div2'));//Clicking on div2 will still alert. You should be fine using html() as above. Be careful in IE9 <though. From jquery docs:
Note. In Internet Explorer prior to version 9, including version 9, installing the text content of an HTML element can damage the text nodes of its children, which are removed from the document as a result of the operation. If you keep references to these DOM elements and need to be immutable, use .empty (). Html (string) instead of .html (string) so that the elements are removed from the document before the new line is assigned to the element.
If you want to keep listeners, you must use delegated event listening. See Documents for on () :
<div id="wrapper"> <div id="div1"> <div id="div2">Original div2</div> </div> <div id="div3"></div> </div> $('#wrapper').on('click', '#div2', function() {...});