Search code examples
javascriptjqueryobjectpointers

jquery remove() does not remove reference


strong textWhen i create a reference to a DOM object and then remove it the reference is still there.

var test = $("#test")
console.log(test.length); //1
$('#test').remove();
console.log(test.html()); //test
console.log( $("#test").html() ) //undefined

I think this has to be a new feature/bug of jquery; we recently updated. Major systemic issue if this is true that was not present prior to update(pretty sure)

EDIT: The variable is a clone of the element? Its supposed to be a pointer/reference to the element.

EDIT 2: Does the ability to have a pointer to an DOM object not make sense? I want to have a variable that points to the DOM object so i can monitor it without having to do a selector on the DOM everytime.

EDIT 3: simplified example of lots of functions altering a globally scoped object

GLOBAL_OBJECT ={};

function add_image(itemName =="item1"){
        //fetch item and insert into dom
        $(body).append(largeImage);
        GLOBAL_OBJECT[itemName] = $(largeImageID);
}

function move_me(itemName){
    if(itemName in GLOBAL_OBJECT && GLOBAL_OBJECT[itemName].length){
        GLOBAL_OBJECT[itemName].css(
            "top":aTop,
            "left":aLeft
        )
    }else{
       add_image(itemName);
    }
}
function hideImages(){
    $('canvas.largeImages').remove();
}

add_image();
hideImages();
move_me("item1");

fiddle

From Manual:

searches through the DOM for any elements that match the provided selector and creates a new jQuery object that references these elements


Solution

  • Let's break this down.

    var test = $("#test")
    

    This creates a new jQuery object based on a search for an element in the DOM with id "test".

    console.log(test.length); //1
    

    Because the length of the jQuery element is 1, we know that there is in fact such an element.

    $('#test').remove();
    

    This tells jQuery to unlink the element from the DOM. This means that the parent element no longer refers to the previously-located DOM element. However, the element, as an object, still exists.

    console.log(test.html()); //test
    

    This makes sense, because, as I said, the element and all its child nodes still exist, including the text node that apparently contains the text "test". They are not in the DOM, but they have not vanished from our plane of reality. When the jQuery object goes out of scope and is eventually garbage-collected, the DOM element and its children will eventually also be garbage-collected.

    console.log( $("#test").html() ) //undefined
    

    This also makes sense. The element with id "test" was removed from the DOM, so this new attempt to locate it by creating a new jQuery object results in a zero-length instance, and therefore .html() returns undefined.