Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 532
finferflu Avatar asked Dec 15 '10 14:12

finferflu


People also ask

What is the use of load () function?

The load() method loads data from a server and puts the returned data into the selected element.

How do I select something in jQuery?

The select() method is an inbuilt method in jQuery which is used when some letters or words are selected (or marked) in a text area or a text field. Syntax: $(selector). select(function);

What is the use of jQuery load method?

The Load() method in jQuery helps to load data from server and returned into selected element without loading the whole page. Syntax: $(selector). load(URL, data, callback);

How do I select a specific tag in jQuery?

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.


2 Answers

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();
});
like image 133
SLaks Avatar answered Nov 15 '22 15:11

SLaks


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.');
});
like image 34
Simon Avatar answered Nov 15 '22 16:11

Simon