Marcatectura
Marcatectura

Reputation: 1695

.load() Method on a non-DIV element

I've built a small site to test using the .load() method to load the contents of an element. While .load works if I place the target element inside <div> tags, I can't get it to work on just the target element, a page title in <h1> tags. Is there a way to load content using .load() without placing <div> tags around every affected element in my HTML?

My HTML for page 1:

<body>
<h1 id="pagetitle">Page 1</h1>
<p>Some paragraph text</p>
<a id="page2">page 2</a>
</body>

For page 2, the HTML is the same, except the title is <h1>Page 2<h1>.

My jQuery:

$('a#page2').click(function () {
$("#pagetitle").load("page2.html #pagetitle > *");
});

From everything I've read, clicking #page2 should load the contents of the #pagetitle tags from page2.html, but the content isn't added - instead, the content ("page 1") just dissapears.

However, if I add <div> tags around the <h1> elements and load the divs instead:

$("div#pagetitle").load("page2.html div#pagetitle > *");

The content is replaced. However, in the interest of keeping my HTML uncluttered, I'd like to avoid this if there's a better way.

Upvotes: 0

Views: 94

Answers (1)

Ram
Ram

Reputation: 144659

> * selects direct children of the #pagetitle element, in your markup h1 element doesn't have any descendant element, so the query fails and it returns nothing, remove the > * selector and it should work. However, it will add the loaded h1 element to the the current h1 element, jQuery .load() methods uses $.get() utility function, you can use this function to replace the element or change the innerHTML property of the current h1 element. This gives you more control over the loaded html.

$('#page2').click(function(event) {
   // event.preventDefault();
   $.get('page2.html', function(data) {
       $("#pagetitle").html(function() {
            return $(data).find('#pagetitle').html();
       });
   }, 'html');
});

Upvotes: 1

Related Questions