Load() with page and ID

130 Views Asked by At

I am trying to load an ID from a page with jQuery's load(). Here is the HTML of the loaded page:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>
</head>

<body>
        <section id="content" class="contentPage">
        <h3>Home</h3>
        <p>
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean id eros orci. Nam id interdum enim. Ut mauris enim, scelerisque a pellentesque in, molestie eget sem. Ut sagittis erat eget elit euismod laoreet. Vivamus odio mauris, aliquam sed ornare non, tempus nec augue. Proin id lectus elit. Donec pharetra viverra lectus, pellentesque sollicitudin magna gravida pellentesque. Quisque tristique, libero at pulvinar rutrum, neque nunc tincidunt lorem, sit amet varius lorem leo sit amet mi. Quisque vehicula diam in libero aliquet dapibus. Nullam eget arcu a sapien scelerisque fermentum. Integer suscipit magna sed quam aliquet mattis. Suspendisse in erat eu nisi hendrerit bibendum. Aliquam blandit malesuada metus. Duis dapibus consequat ultrices.
        </p>
        </section>
        <!-- end Page1 -->
</body>
</html>

From this I only wish to load the #content section (and for compatibility reasons I cannot get rid of everything but that section). I am working with variables to call this function, but this doesn't seem to work:

var firstLink = $("ul > li:first-child > a");   
$("#sectionContainer").load("./" + firstLink.attr("href") + " #content");

In which the variable firstLink.attr("href") returns a link such as Pages1.html. When the last part ( + " #content") is left out, the script works as it should.

I thought this would work, because jQuery's documentation states you can do the following:

$('#result').load('ajax/test.html #container');

Any idea what I am doing wrong? Or can't you add this kind of text to a variable in jQuery?

2

There are 2 best solutions below

0
On BEST ANSWER

If you are using

var firstLink = $("ul > li:first-child > a");   
$("#sectionContainer").load("./" + firstLink.attr("href") + " #content");

Then in the page referred by first link should have an element (for example a div or a section) with ID content

As in your case your page (first link) contains id Pages1 you can use #Pages1 in place of #content

0
On

this feature works, just try instead and you should have a single "home" text in your page :

  $(document).ready(function() {
    $("#content").load(". h3"); // reload in the same page
  });

The most common problem is the url in the first parameter of .load(). Look for 404 in your network console. Then, try :

$("#sectionContainer").load("./Pages1.html #content");

Do you have <base> in your page ? absolute urls ?