3

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.

1
  • And what did foo.html contain? Commented Jun 22, 2011 at 15:41

3 Answers 3

8

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'));
});
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.