Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If I overwrite html, is it removed from the dom?

Tags:

jquery

dom

Imagine 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>');

do I end up with problems because I didn't use .remove() to remove #div2 from the dom, or does clearing the html in this way do that for me?

What if div2 contained some javascript that attached a handler, say something like

$('#div2').on('click',function() { ... });

would that also be removed, or would I need to off() it?

like image 473
Ben Holness Avatar asked Apr 16 '13 18:04

Ben Holness


2 Answers

do I end up with problems because I didn't use .remove() to remove #div2 from the dom, or does clearing the html in this way do that for me?

No, jQuery will use .remove for you internally (technically it uses cleanData, but it performs the same cleanup.)

Events will be lost, so you'll have to rebind them.

like image 189
Kevin B Avatar answered Sep 23 '22 10:09

Kevin B


As your Event's will be lost you can use .on() like this , so you don't need to rebind event's

$(document).on('click','#div2',function() { ... });
like image 37
Mohammad Adil Avatar answered Sep 21 '22 10:09

Mohammad Adil