Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Question

What's the full code to enable jQuery on a page and then use it to replace the contents of a DIV with HTML text from an external file?

Background

I'm brand new to jQuery and I'm eager to work with it so I can learn it. I have a site where I need to replace the contents of the same div (a footer) that exists on every page. Fortunately, each of these pages already imports the same header file. So I'm going to modify that header file with some jQuery magic! I'm having trouble finding full examples and I figured other's might have similar questions. Who better to ask than the SO gurus?

Example

Given a basic HTML file Example.html:

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

And an external file includes/contentSnippet.html containing a snippet of html:

<p>
    Hello World!
</p>

What would the new Example.htmlfile be that would link the proper jQuery libraries (from the ./js directory) and replace the div's contents via jQuery?

like image 562
gMale Avatar asked Feb 26 '11 05:02

gMale


1 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:

  1. I've linked the jquery libraries directly from jQuery's public CDN (which is allowed and encouraged)
  2. You can find the documentation for jQuery's load() function right here.
like image 54
Lee Avatar answered Oct 19 '22 09:10

Lee