4

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>
labrassbandito
  • 535
  • 12
  • 25
  • Possible duplicate of [jQuery: HTML is not updated after manipulating paths](http://stackoverflow.com/questions/4194691/jquery-html-is-not-updated-after-manipulating-img-src-paths) – Apb Jan 11 '16 at 10:11

1 Answers1

8

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>
Liam Galvin
  • 706
  • 3
  • 12
  • The next problem. The update of the *src* attribute is not reflected in the rendered HTML. If I look via Firebug in the HTML code, the new *src* paths are up to date. – labrassbandito Nov 16 '10 at 13:21
  • $("#content").load("additonal_content.html #content table", function() { $("#content").find("img").each(function() { $(this).attr("src", "new_folder/" + $(this).attr("src")); }); }); – labrassbandito Nov 16 '10 at 13:22
  • Hmm, might be best if you post this as a new question. Do you have a live site we can look at? – Liam Galvin Nov 16 '10 at 13:24
  • Here we go: http://stackoverflow.com/questions/4194691/jquery-html-is-not-updated-after-manipulating-img-src-paths Unfortunately, I have no working live example, yet. – labrassbandito Nov 16 '10 at 13:38