jQuery: Is it possible to assign a DOM element to a variable for later use?

Posted by Braxo on Stack Overflow See other posts from Stack Overflow or by Braxo
Published on 2010-04-23T15:11:30Z Indexed on 2010/04/23 15:13 UTC
Read the original article Hit count: 129

Filed under:
|

I'm working on a project that is using jQuery, which I'm much more familiar with Mootools.

I'll start with my code first.

var customNamespace = {
    status: 'closed',
    popup: $('#popup'),

    showPopup: function() {
        // ...  
    }
}

$(document).ready(function(){
    console.log($('#popup'));
    console.log(customNamespace.popup);
    console.log($(customNamespace.popup));

    $('#popup').fadeIn('slow');
    (customNamespace.popup).fadeIn('slow');
    $(customNamespace.popup).fadeIn('slow');
});

My goal is to not have jQuery traverse the DOM everytime I want to do something with the #popup div, so I wanted to save it to a variable to use it throughout my script.

When the page loads, the console prints out the object 3 times as I would expect, so I assumed that for each method, the fadeIn would just work. But it doesn't, only

$('#popup').fadeIn('slow');

Actually fades in the div.

Even if I remove my namespace hash, and just save the object to a global variable, and do a

var globalVariable = $('#popup');
.
.
.
globalVariable.fadeIn('slow');

Also does not work as I thought it would. Can jQuery do what I am trying to do?

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about JavaScript