简体   繁体   中英

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);
});

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.

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");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM