Alex
Alex

Reputation: 1606

How to change title of page on .load() with new title of loaded page in jQuery

I’m confused about the .load() and $.ajax. I have the following jQuery code in my index.html:

$('.load_ext').click(function(e) {    
    var url = $(this).attr("href");
    parentContainer.append($(document.createElement("div")).load(url + ' #content_to_load').html('<p class="loading">Loading&#8230;</p>').hide().fadeIn('slow'));
})

and HTML:

<a href="test.html" class="load_ext">test</a>

In the example above, I’m loading partial content from the test.html (the content of id #content_to_load). I also want to grab the title of that test.html page and replace the index.html title page with that one.

I tried doing something like:

var url = $(this).attr("href");
parentContainer.append($(document.createElement("div")).load(url + ' #content_to_load', function() { 
     console.log($(document).attr('title'));
}).html('<p class="loading">Loading&#8230;</p>').hide().fadeIn('slow'));

without any luck. It gives me the current page title. How can I replace the title by doing something like:

$('title').text(newPageTitle);

Thanks!


EDIT: Thanks to @Jeff Schafer, @dystroy, and @zeroflagL I managed to solve this problem. Here’s the changed code:

var url = $(this).attr("href");
parentContainer.append($(document.createElement("div")).load(url + ' #content_to_load', function(responseText) {
  var title = responseText.match(/<title>([^<]*)/)[1];
  document.title = title;
}).html('<p class="loading">Loading&#8230;</p>').hide().fadeIn('slow'));

Upvotes: 2

Views: 4818

Answers (3)

iJade
iJade

Reputation: 23791

try this code to change page title

document.title = newPageTitle;

hope it helps

Upvotes: 1

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382092

The main problem with load is that jQuery, when building the DOM fragment, strippes what isn't the body. You can use this to get the title of a distant page :

$.get(url, function(html){
    var matches = html.match(/<title>([^<]*)/);
    if (matches.length>0) {
        var title = matches[1];
        document.title = title;
    }
});

Note that this won't work if the distant page is from a different origin and doesn't specifically allow cross-domain requests.

Upvotes: 3

a better oliver
a better oliver

Reputation: 26828

You can get the title of the new page through the responseText:

.load(url + ' #content_to_load', function(responseText) {

repsonseText is literally text, though, the source code of the page. You can use regular expressions, for instance, to extract the title of test.html. Then you can change the title with document.title = newTitle.

Upvotes: 2

Related Questions