Search code examples
javascriptdom-events

How to remove element from DOM tree with the event handler


This is the element which I want to remove:

<div id="tobeRemoved">
    <div class="eventAttached"></div>
    <div>
        <div class="eventAttached"></div>
    </div>
</div>

And its child may be have event attached.

And now I want to remove it from the DOM tree; I know I can use this:

var ele=document.getElementById("tobeRemoved");
ele.parentNode.removeChild(ele);

But how about the events? Are they cleared at the same time auto?

BTW, I prefer to a cross-browser solution.


Solution

  • You could try this if you know the event type:

    function removeEventHandler(elem,eventType,handler) {
     if (elem.removeEventListener) 
        elem.removeEventListener (eventType,handler,false);
     if (elem.detachEvent)
        elem.detachEvent ('on'+eventType,handler); 
    }
    

    or jQuery's .unbind() function.