JQuery: replace the contents of the DIV with html from an external file. Full example?

Question

What is the complete code to enable jQuery on the page, and then use it to replace the contents of the DIV with HTML text from an external file?

Background

I am new to jQuery, and I really want to work with him to learn this. I have a website where I need to replace the contents of the same div (footer) that exists on every page. Fortunately, each of these pages already imports the same header file. So I'm going to change this header file with some jQuery magic! I had trouble finding complete examples , and I thought that others might have similar questions. Who better to ask than an SO guru?

Example

Given the basic HTML file Example.html :

 <html> <head> </head> <body> <div id="selectedTarget"> Existing content. </div> </body> </html> 

And the external file includes/contentSnippet.html containing the html fragment:

 <p> Hello World! </p> 

What will be the new Example.html file that will link the correct jQuery libraries (from the. / Js directory) and replace the contents of the div through jQuery?

+8
javascript jquery jquery-selectors
source share
2 answers

ok I'll bite ...

 <html> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-1.5.1.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $('#selectedTarget').load('includes/contentSnippet.html'); }); </script> </head> <body> <div id="selectedTarget"> Existing content. </div> </body> </html> 

Notes:

  • I linked the jquery libraries directly to the jQuery public CDN (which is allowed and approved )
  • You can find the documentation for the jQuery load() function here .
+15
source share

To use jQuery on your page, it is usually recommended that you place the script in front of the closing body tag to save the rest of the page content to block for loading. He also recommended using code from Google’s CDN for various benefits. Here are some useful links: http://encosia.com/2008/12/10/3-reasons-why-you-should-let-google-host-jquery-for- you / and http://encosia.com/2010/09/15/6953-reasons-why-i-still-let-google-host-jquery-for-me/ .

jQuery Tutorials: http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery :

 <script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script> <script> // your script will go here </script> </body> 

To replace the contents of a div with the content from another file, this is done using an AJAX request:

 $('#selectedTarget').load('includes/contentSnippet.html'); 

Obviously, there are many opportunities to learn and much more to manage and optimize your pages. I would definitely recommend reading the jQuery API documentation to find out more: http://api.jquery.com

+2
source share

All Articles