theMayer
theMayer

Reputation: 16167

Find the title of a dynamically-loaded HTML page

I am experimenting with dynamically-loading content (e.g. when the user clicks the link, the content is loaded in the background instead of the whole page refreshing).

I can't figure out how to get the title from the DOM Elements returned by jQuery.parseHTML. The API documentation states that it "uses a native DOM element creation function to convert the string to a set of DOM elements, which can then be inserted into the document."

The following code does not get the "title" node from the set. When I look at the list in the chrome debugger console, I see the list, formatted with each element in the array appearing like [#: type] (e.g. [1: title] as the title node is the second element in this example). I can see it there, and click on it in the debugger, but can't figure out how to access it in a logical way from my code.

Can someone please help?

$('#mainContent').load(url, function (response, status) {
        if (status != "success") {
            $('#mainContent').hide();
            $('.notFound').show();

            document.title = getTitle("Page Not Found");
        }
        else {
            var title = jQuery.parseHTML(response)['title'].innerText;
            title = getTitle(title); //does some validation on the input (e.g. not blank, etc).
            document.title = title;
            $('#mainContent').show();
        }
    });

Upvotes: 1

Views: 119

Answers (1)

Troy Cosentino
Troy Cosentino

Reputation: 4778

This should work (you may have to change TITLE to title):

$.each( jQuery.parseHTML(response), function( i, el ) {
  if(el.nodeName === "TITLE") {
    title = $(el).html();
    return false; // break out of the each loop
  }
});

Edit: small change should make it a little quicker for large amounts of DOM nodes

Upvotes: 3

Related Questions