Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AJAX: Getting the title of the loaded html document (jquery)

Tags:

html

jquery

ajax

I am loading an html page within the body of a landing page via jquery and ajax. I need the <title>Page Title</title> from the loaded document for the landing page.

I have tried this, but no luck:

$.ajax({
    url: "test.htm",
    cache: false,
    dataType: "html",
    success: function(html){
            $('#main-load').html(html);
            $('#greeting').append($(html).find('title').text());
        }
});

I have also tried a few other methods, but no luck. Any ideas?

Thank you!

EDIT: test.htm is a very simple document.

Example:

<html>
<head>
<title>Page Title</title>
<style>
....
</style>
</head>
<body>
....
</body>
</html>
like image 933
Sunburnt Ginger Avatar asked Jan 20 '23 00:01

Sunburnt Ginger


1 Answers

As Pekka said, it does strip the head from the loaded document, so you'll have to parse it out of the raw text with a regular expression: (Let me know if this works)

var title = html.match("<title>(.*?)</title>")[1];
like image 190
penguinrob Avatar answered Jan 30 '23 21:01

penguinrob