I use an object literal to collect various DOM elements I add dynamically because I want to be able to reference them by variable (code below is simplified, there would be much more, like events and so on):
ui = {
header : $('<div id="header"></div>').appendTo('body').css('color','#009'),
footer : $('<div id="footer"></div>').appendTo('body').css('color','#990')
}
Now I wish I could just add other objects to this, but it will throw an error:
ui = {
header : $('<div id="header"></div>').appendTo('body').css('color','#009'),
footer : $('<div id="footer"></div>').appendTo('body').css('color','#990'),
headerSpecial : $('<span>some header</span>').appendTo(ui.header) // this line will cause an error "ui is not defined"
}
I suppose this is because until the ui object is closed, I can't reference anything inside yet. SO I would have to separate out these things into separate objects. But is there some way I can do it all in a single object? Should I wrap some stuff in anonymous functions and then call them?