lynxidngo
lynxidngo

Reputation: 149

jQuery how to use DOM objects from external source

I have the following source tree:

source
|-html
|  |-div1.html
|  |_div2.html
|-js
|  |_bundle.js
|_index.html

And my index.html looks as follows:

<!DOCTYPE html>
<html>
  <head>
    <script type="text/ecmascript" src="./js/bundle.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  </head>
  <body>
    <div id="div1"></div>
    <div id="div2"></div>
    <script>
      $(document).ready(function(e){
        $('#div1').load('./html/div1.html');
      });
      $(document).ready(function(e){
        $('#div2').load('./html/div2.html');
      });
    </script>
  </body>
</html>

How do I use jQuery such that I can manipulate <div> in the external html sources of div1.html and div2.html? Assuming that both of them contain the following code segment:

<div id="tParagraph">
  <p>This is a paragraph</p>
</div>

Upvotes: 2

Views: 49

Answers (1)

Suresh Atta
Suresh Atta

Reputation: 121998

First thing you should note is id's must be unique as you saying both files have same HTML.

And once you loaded successfully, you can access those elements like any other DOM elements.

$("#tParagraph")

And inorder to make sure that it loaded, you must use a callback.

 $('#div2').load('./html/div2.html', function(){

  // loaded.
});

putting it all together

$('#div2').load('./html/div2.html', function(){
   $("#tParagraph").dosomeThing();
});

Upvotes: 2

Related Questions