pion
pion

Reputation: 3613

jQuery selector for dynamically generated element

I have the following html snippet:

<div id="contentX"><h1>MyHeading1</h1></div>

I could select with jQuery snippet syccessfully with the following:

console.log($('#contentX h1'));

The output is

[<h1>​MyHeading1​</h1>​]

However, it did not work when I dynamically loaded the contents. For example,

html code snippet:

<div id="content"></div>

jQuery code snippet:

$('#content').load('foo.html')); // the content is loaded correctly with <h1> tag

jQuery code snippet does not work:

console.log($('#content h1')); // it returns []. I was expecting to return something.

I am wondering if this is a similar behavior like event binding: .click() vs .live().

Thanks in advance for your help.

Upvotes: 3

Views: 1504

Answers (3)

Jon Grant
Jon Grant

Reputation: 11520

The load function is asynchronous, meaning it starts the load and then it carries on in the background and then continues to execute the rest of your script.

It does not wait for the load to complete first.

You can attach a function to the load call to tell jQuery to do it once the load is complete.
Here is an example:

$('#content').load('foo.html', function() {     
    console.log($('#content h1'));
});

Upvotes: 8

Ram Bulatnikov
Ram Bulatnikov

Reputation: 21

Load is one of jQuery's shorthand AJAX methods, and same as animation functions and others, it doesn't wait until it finishes loading the external file (foo.html) in order to run. Try putting the console.log (or whatever you want there) as a callback:

(...).load([url], function() {
  console.log("whatever");
}

You can also use the callback to catch errors when trying to fetch the page:

(...).load([url], function(response, status, xhr) {
  if (status == "error") {
    alert("Well, that didn't really work, here's the reason why:" + xhr.statusText);
  }
}

Refer to the .load page on jQuery's API to dig further: http://api.jquery.com/load/

Hope this works for you

Upvotes: 1

Jose Faeti
Jose Faeti

Reputation: 12314

$('#content').load('foo.html', function () {
    console.log($('#content h1'));
});

Upvotes: 2

Related Questions