Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Loading external HTML content; Access to elements inserted fails

I would like to load a table element from another HTML (additional_content.html) into the current HTML via jQuery. I managed to load the content but I am not able to access the elements inserted as if they were not inserted. However, when inserting an alert statement just after the load statement, I am able to access the elements of the table inserted via load. It appears to me that the DOM tree is not updated immediately.

The code fragment within the parent document looks like this:

<div id="content"></div>
<script>
  $("#content").load("additonal_content.html #content table").hide();
  $("#content").find("img").each(function() {
    alert("test");
  });
</script>

And the table within *additional_content.html" is (excerpt):

<table>
  <tr>
    <td><img src="image1.gif"></td>
    <td>some text...</td>
  </tr>
  <tr>
    <td><img src="image2.gif"></td>
    <td>some text...</td>
  </tr>
</table>
like image 426
labrassbandito Avatar asked Feb 25 '23 19:02

labrassbandito


1 Answers

It looks like the content hasn't loaded yet when it hits the 'find' statement.

Try using a callback, a la:

<script>
$("#content").load("additonal_content.html #content table",function(){
 $("#content").find("img").each(function() {
    alert("test");
 });
});
 </script>
like image 84
Liam Galvin Avatar answered Apr 09 '23 18:04

Liam Galvin