2

I'm trying to run an answer I found at the following link: Asynchronously Load the Contents of a Div

But when I do, I get errors that I don't quite understand.

My code:

$(document).ready(function() {
  $("#first").load(function() {
    $("body").append($("<div></div>").attr({
      id: "second"
    }).text("Second"));
    $("#second").load(function() {
      $("body").append($("<div></div>").attr({
        id: "third"
      }).text("Third"));
    });
  });
});
<html>

<head>
  <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-
3.2.1.min.js"></script>
</head>

<body>
  <div id="#first">First</div>
</body>

</html>

The error I get back from Chrome is extensive. But here's the highlights:

Uncaught TypeError: a.indexOf is not a function
    at r.fn.init.r.fn.load (jquery-3.2.1.min.js:4)
    at HTMLDocument.<anonymous> (temp.html:6)
    at j (jquery-3.2.1.min.js:2)
    at k (jquery-3.2.1.min.js:2)

Any ideas?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • Possible duplicate of ["Uncaught TypeError: a.indexOf is not a function" error when opening new foundation project](https://stackoverflow.com/questions/38871753/uncaught-typeerror-a-indexof-is-not-a-function-error-when-opening-new-foundat) – Ivan Minakov Aug 31 '17 at 06:34
  • 1
    `$("#first")` does not equal `
    `
    – StudioTime Aug 31 '17 at 06:36
  • There's no `load` event for `
    `. Only elements that fill themselves in from external resources, like `` and `
    – Barmar Aug 31 '17 at 06:40

2 Answers2

8

This error might be caused by jquery event aliases like .error, .load or .unload. These are deprecated since jQuery 1.8. You need to replace them with .on() to register listeners instead. Example:

$(window).load(function(){
  ...
});

becomes:

$(window).on('load', function(){
 ...
});

So try using with .on()

Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
0

Your first issue is resolved by using:

$("#first").on('load', function() {
  *code to be executed*
}

.load has been deprecated since jQuery 1.8

The second issue you mention that only the first div is created happens because you are trying to execute the next function to create the third div when the second div is loaded but in reality the second div is not loaded since you are appending it so no load is occurring in this case.

You can just append one after the other and they will appear in order assuming that is what you are trying to do.

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135