Pergunta

If I use document.getElementById to store a DOM element in a variable, and then remove the element from the DOM with the removeChild method, the object stored in the variable is not updated to a null reference. For example:

<div id="a">

</div>

<script>

  var a = document.getElementById('a');

  alert(a); // Alerts "[object HTMLDivElement]".

  a.parentNode.removeChild(a);

  alert(a); // Still alerts "[object HTMLDivElement]".

</script>

Is there any way to make the DOM element reference stored in the a variable more "live" in that it could detect when the element is removed from the DOM and thus be updated to null or whatever?

Thank you in advance.

Foi útil?

Solução

You can't, because you store in a variable, just call var a = document.getElementById('a') when you need check.

var a = document.getElementById('a');

alert(a); // Alerts "[object HTMLDivElement]".

a.parentNode.removeChild(a);

a = document.getElementById('a');

alert(a); // "undefined".

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top