0

I've loaded file in div

$("#div").load("file.txt");

That file has html images .
I want to access them by $('#div>img') (or other selectors), but nothing happens. If they were in page initially, there are no problems.

How can you access loaded content by jQuery as part of the usual page?

Qiao
  • 16,565
  • 29
  • 90
  • 117

3 Answers3

1

See jquery doesn't see new elements for one possible problem you might be having. Use the change method to wait until they enter the DOM. e.g.

$("#div").load("file.txt");

$('#div>img').change(function(){
  var images = $('#div>img');
  // Do something...
} 
Community
  • 1
  • 1
Jesse Millikan
  • 3,104
  • 1
  • 21
  • 32
1
$("#div").load("file.txt");
$("#div > img")...  // file.txt hasn't finished loading yet

Will probably not work, since loading the file happens asynchronously and takes some time, and the content is simply not there yet when you try to access it. For this reason, you can specify a callback that is guaranteed to run after the load() has finished:

$("#div").load("file.txt", function () {
    // file.txt has finished loading, this should work:
    $("#div > img")...
});
deceze
  • 510,633
  • 85
  • 743
  • 889
1

The content loaded (supposedly through Ajax) is rendered as a text string. It's up to you to load it into the DOM using .innerHTML and such. In jQuery you can use .html() to load the content inside the DOM and then you're going to be able to access it through standard jQuery DOM selectors.

Luca Matteis
  • 29,161
  • 19
  • 114
  • 169
  • it is walkaround, but point is in using dynamical loading. file is big, should be loaded only when neded – Qiao Mar 03 '10 at 08:50
  • jQuery should interpret the loaded content as HTML, there shouldn't be a need for doing anything else manually. http://api.jquery.com/load/ – deceze Mar 03 '10 at 08:51