technopeasant
technopeasant

Reputation: 7939

parse javascript get html results for page title

Need to snag page title and other meta from jQuery's $.get results. Read somewhere on here (can't seem to find the question though - sorry!) that it only returns elements within body. That said, if I log the results to the console I see a massive array of data that includes the title and meta tags.

So the question is simple- how can I navigate the array to pull out the title?

Here's an example. The below example returns content as an HTML object, but title returns undefined. Makes sense if only the body is returned. That said, logging data prints the entire pages HTML from top to bottom. Logging thiis prints the page as an array, where I can see an entry for title, whose innerHTML has the page title. So - how should title's value be assigned?

Thanks for your help!

JavaScript

$.get(target, function(data){

    var thiis   = $(data),
        content = thiis.find('#pageMain'),
        title   = thiis.find('title');

    console.log(data, thiis);
});

Upvotes: 1

Views: 1393

Answers (2)

epascarello
epascarello

Reputation: 207501

jQuery does not parse the doctype, html, head, and body elements. It sets your whole page that you retireved with the GET request as the innerHTML of a div. You only get back a collection of the resulting element so the title element and id of pageMin are not able to be found with find(). You would need to use filter().

$.get(target, function(data){
    var nodes   = $(data),
        content = nodes.filter('#pageMain'),
        title   = nodes.filter('title');
    console.log(content,title);
});

In order to use find() you would need to set the innerHTML of a div with the data and query off that parent node.

Upvotes: 4

scrappedcola
scrappedcola

Reputation: 10572

Wrap the returned data in a div first then make your selection.

$.get(target, function(data){
    var $wrap = $("<div></div>").append(data);
    var title = $wrap.find("title");
});

Upvotes: 1

Related Questions