I have a javascript object as such (simplified).
var MyObject = (function(){
var propertyOne = $('.links li:first-child');
var propertyTwo = $('.links .active');
function startup()
{
propertyOne.addClass("class"); //Works
propertyTwo.addClass("class2"); //Does not work
$('.links .active').addClass("class2"); // Works
}
return {
init: function()
{
startup();
}
}
});
What’s the difference in the way I’m selecting propertyOne and propertyTwo? I don’t understand why
propertyOne.addClass("class"); //Works
$('.links .active').addClass("class2"); // Works
Yet…
propertyTwo.addClass("class2"); //Does not work
Can anyone help explain this to me?
The DOM element for propertyTwo must not exist at the time that
var propertyTwo = $('.links .active')is called, whereas it does oncestartup()is called.To confirm this, we’ll need more information about your script. For example, what I previously described could occur if
MyObjectis created prior to the DOM being fully loaded, and then you call theinit()method after the DOM is fully loaded (or at least after the element corresponding to$('.links .active')has been loaded.Regardless, you should really focus on learning how to debug something like this along with why this specific attempt is not working. The main step in this process is to log to the console
propertyTworight after the linevar propertyTwo = $('.links .active'). If the console shows[](in Chrome at least), that means no elements were matched, which would support what I said is happening.