Ben
Ben

Reputation: 16679

Accessing elements which have been added to the DOM via file loaded using .load()

I am using jQuery .load() to load a php-file. This php-file echos out a new div. This div contains an attribute "title", whose value I need to get in my js-file.

// file.php
echo '<div id="max_page" title="' . $max_page . '"></div>';

// js
$("someElement").load("file.php");
var num = $("div#max_page").attr("title");

This results in num = "undefined". I am assuming the reason for this is that the div#max_page gets added to the DOM after the initial $(document).ready was performed and hence jQuery simply doesn't know of its existence. Is that right?

How can the problem be solved? (I tried experimenting with .live() but couldn't get it to work for me)

Upvotes: 1

Views: 75

Answers (3)

David Wick
David Wick

Reputation: 7105

the file hasn't loaded when you set num. use a callback.

$("someElement").load("file.php", function () {
   var num = $("div#max_page").attr("title");
});

Upvotes: 0

mkilmanas
mkilmanas

Reputation: 3485

You're right on thinking that your timing is wrong :)

// js
$("someElement").load("file.php", function(){
    var num = $("div#max_page").attr("title");
    // here you can do with num whatever you need
});

The function passed as a second argument will be executed immediately after file.php is loaded into someElement, thus guaranteed that the title attribute will exist at this point.

Upvotes: 0

Niklas
Niklas

Reputation: 30002

When you check the num it hasn't been added to the DOM yet as the ajax hasn't finished loading the page into the DOM yet. Do it in the complete callback of load:

$("someElement").load("file.php",function(){
var num = $("div#max_page").attr("title");
});

Upvotes: 1

Related Questions