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?

asked Mar 3, 2010 at 8:28
4
  • can you provide a sample of what's inside file.txt? Commented Mar 3, 2010 at 8:30
  • 1
    Are you trying to access them immediately, or are you actually waiting for the load to complete (callback)? Commented Mar 3, 2010 at 8:34
  • 2
    Are you sure you accessing them after file has been loaded and HTML got inserted into DOM? Commented Mar 3, 2010 at 8:34
  • <img src='images/jp.gif' /> .live solved the problem. it was after ful loading Commented Mar 3, 2010 at 8:57

3 Answers 3

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...
} 
answered Mar 3, 2010 at 8:36
Sign up to request clarification or add additional context in comments.

Comments

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.

answered Mar 3, 2010 at 8:39

2 Comments

it is walkaround, but point is in using dynamical loading. file is big, should be loaded only when neded
jQuery should interpret the loaded content as HTML, there shouldn't be a need for doing anything else manually. api.jquery.com/load
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")...
});
answered Mar 3, 2010 at 8:38

1 Comment

Ah! Good thought...why didn't I think of that!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.