1

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'); 
1
  • thanks for the answers, you guys answers the questions in a clear and nice way, I hope someday I can contribute a bit.
    – webberpuma
    Commented Jul 1, 2010 at 12:30

3 Answers 3

3

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'); 
});
1
$.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

1

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.