How to select an element loaded through the jQuery load() function?

14,140

Solution 1

The load function is asynchronous.
Your next line runs before the content is loaded.

You need to put your code inside the load function's callback, so that it will only run after the new content is loaded:

$('#container').load('content.html', function() {
    $('.elementInContentHTML').fadeIn();
});

Solution 2

You could try using the callback for when load completes? See http://api.jquery.com/load/

$('#result').load('ajax/test.html', function() {
  alert('Load was performed.');
});
Share:
14,140
finferflu
Author by

finferflu

Updated on June 18, 2022

Comments

  • finferflu
    finferflu almost 2 years

    I am currently having trouble with the following (here is some sample code first):

    <div id="container"></div>
    
    <script type="text/javascript">
        $('#container').load('content.html');
    
        $('.elementInContentHTML').fadeIn();
    </script>
    

    In short, I want to be able to access elements that have been dynamically added to a page without attaching them to event handlers.

    I know about the live() method, but I do not want to bind my action to any event, i.e. I just want to run some actions with these new elements without clicking them, focusing, blurring, etc.