when i use jquery to create an element(a div, for example) in a callback function, it doesn’t allow me to manipulate the newly created element outside the callback function, how can I get around this?
here is the example:
$.get('menu.xml',function(data){
//create a new element with an ID called "#newElement"
})
//I can't select the element outside the callback function so the following code dosen't work:
$('#newElement').css('background','black');
You can select it outside, but not yet, that
$.get()callback takes some time to run (it has to get the data from the server, the callback happens later, when that finishes), so when you do this:That element isn’t there yet (and so the selector doesn’t find anything…it’s running before that callback creating it does), you need to wait until the callback finishes before continuing any code that needs elements created by it. Like this: