Rich
Rich

Reputation: 5731

Accessing a jQuery element reference as an object property

I'm trying to set an element as a property of an object using jQuery. When I make a direct reference to the jquery object, it works, however when I make the reference through the calculator object, it doesn't.

How do I fix this?

var calculator = {

    settings: {
        displayNumber: $('.dispNumber'),
        modNumber: $('.modNumber')
    }
}

window.onload = function(){
    console.log( $('.dispNumber').html() ); //this one works    
    console.log( calculator.settings.displayNumber.html() ); //this one doesn't
}

Upvotes: 2

Views: 207

Answers (3)

OneOfOne
OneOfOne

Reputation: 99234

Since you are using jQuery, you should put everything handling the DOM inside either :

$(function() {
    //code here will always run after the DOM is ready.
    var calculator = {
        settings: {
            displayNumber: $('.dispNumber'),
            modNumber: $('.modNumber')
        }
    };

    console.log( $('.dispNumber').html() ); //this one works    
    console.log( calculator.settings.displayNumber.html() ); //this one doesn't
});

OR

simply add <script>........code.......</script> before your </body>.

The first one is the proper way to handle DOM-related operations.

Edit: reusable object :

var Calculator = function($) {
    this.settings = {
        displayNumber: $('.dispNumber'),
        modNumber: $('.modNumber')
    };
};

Calculator.prototype = {
    log: function() {
        console.log(this.settings.displayNumber.html());
        console.log(this.settings.modNumber.html());
    }
}

$(function(){
    var calculator = new Calculator($);
    calculator.log();
    console.log(calculator.settings.displayNumber.html());
});

Upvotes: 1

Saturnix
Saturnix

Reputation: 10564

Your code works fine. The only reasons why it shouldn't work is that calculator is not instanciated before window.onload.

Remove that issue and everything works. See: http://jsfiddle.net/352Cm/

var calculator = {

    settings: {
        displayNumber: $('.dispNumber'),
        modNumber: $('.modNumber')
    }
}

console.log( $('.dispNumber').html() ); //this one works    
console.log( calculator.settings.displayNumber.html() ); //this one doesn't

Try to console.log(calculator) in window.load and you'll probably see 'undefined' or crashing code.

Upvotes: 0

Daniel A. White
Daniel A. White

Reputation: 190943

If calculator.settings.displayNumber isn't created in a dom ready scope, it won't have the elements.

Upvotes: 2

Related Questions