Search code examples
jquery

Can anyone explain why an element's content still showing after removing


I might sound novice but quite surprising to me and I need to know what is really happening.

I did this:

var elem=$('#div');
 elem.remove();
alert(elem.text());

Surprisingly I still get alert with the element content.

Where as, if I do this

var elem=$('#div');
 elem.remove();
alert( $('#div').text()); //undefined

Solution

  • In your first example, you remove the element from the DOM, but still have the reference to it in your variable, which you then alert it's text.

    In the second example, you again remove the element from the DOM, and then search the DOM again for an element with id div, which is not found, thus returning undefined when it's text is alerted.