简体   繁体   中英

How to extract elements from `head` section of HTML string?

I have a variable ( s ) which holds entire HTML document (as a string). I would like to extract some elements from its head section. With body it is not a problem, I pack entire data into jQuery variable and call find .

But with head section is different story. When I pack it to jQuery object I can see it creates an array for it, and I see the elements I would like to extract (so to this point it works as I would wish). But when I run find against it, jQuery ignores head and its content entirely.

So how to extract the elements from the head ?

Just for the record, currently I am trying to extract link nodes to get urls for CSS files.

For the URL of your CSS files, this regexp should do the trick:

var patt = /.*<link(.*href="(.*)"|.*rel="stylesheet"|.*type="text\/css"){1,}.*>.*/gi;
var array_of_ccs_files = head_as_str.match(patt);
for (var i = 1; i < array_of_ccs_files.length; ++i) {
    console.log(array_of_ccs_files[i]);
}

For top level elements in your DOM, it seems you have to use filter() instead of find().

var html = $.parseHTML('<html><head><meta content="text/html; charset=UTF-8" http-equiv="Content-Type"><link rel="stylesheet" href="/css/inuit.css"><link rel="stylesheet" href="/css/inuit.css"><link rel="stylesheet" href="/css/inuit.css"></head><body></body></html>');

$(html).filter("link").each(function(i, link) {
    alert(link);  
});

This alerts the three links from the string.

You can just query the jQuery object for it...

var sHtmlString = ....;
var oDom = $(sHtmlString);
oDom.find("head > link");

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