Search code examples
phpjqueryjquery-load

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)


Solution

  • 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");
    });