Whenever I generate a new element dynamically using JQuery like this:
$("<div>",{id : "list"}).html("hello").appendTo("body");
and then create a JavaScript object with the selected element like so:
var obj = {el : document.querySelector("#list") }
Surprisingly, even after removing the element, when I print obj.el
, it still shows:
<div id="list">hello</div>
I am able to change the content using obj.el.innerHTML = "foo";
But even after deleting the element with:
$("#list").remove();
The element is still present in the object obj. When printed, obj.el
continues to show:
<div id="list">hello</div>
Why does this happen? Is there a more efficient way to store reference to an element without having to save a complex nested CSS selector which could impact performance?