views:

49

answers:

3

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'); 
+3  A: 

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:

$('#newElement').css('background','black');

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:

$.get('menu.xml',function(data){
  //create a new element with an ID called "#newElement"
  //kick off stuff that uses "#newElement"
  $('#newElement').css('background','black'); 
});
Nick Craver
A: 
$.get('menu.xml',function(data){
     //create a new element with an ID called ".newElement"

     $('<div/>').val(data).attr('id','newElement').css('background','black').append('#container');

})

Try modifying the element within the callback, also try using the class instead of the id

RobertPitt
A: 

Judging from the code you've shown, it seems your trying to manipulate '#newElement' before it exists. The reason for that is '#newElement' is created in the callback of '$.get'.

Its important to remember that asynchronous functions in javascript don't cause the thread to wait, this is why callbacks exist. So, before your callback function for '$.get' has even been executed, you are trying to manipulate '#newElement'.

For instance, if you adjust your code to:

$.get('menu.xml',function(data){

    //create a new element with an ID called "#newElement"
    ....

    $('#newElement').css('background','black');
})

You will find that it works.

Sean Amos