简体   繁体   English

如何从HTML字符串的“ head”部分提取元素?

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

I have a variable ( s ) which holds entire HTML document (as a string). 我有一个变量( s ),可以保存整个HTML文档(作为一个字符串)。 I would like to extract some elements from its head section. 我想从其head提取一些元素。 With body it is not a problem, I pack entire data into jQuery variable and call find . 使用body没问题,我将整个数据打包到jQuery变量中并调用find

But with head section is different story. 但是与head截然不同的故事。 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). 当我将其打包到jQuery对象中时,我可以看到它为它创建了一个数组,并且看到了我想提取的元素(因此到目前为止,它可以按我的意愿工作)。 But when I run find against it, jQuery ignores head and its content entirely. 但是,当我针对它运行find时,jQuery会完全忽略head及其内容。

So how to extract the elements from the head ? 那么如何从head提取元素呢?

Just for the record, currently I am trying to extract link nodes to get urls for CSS files. 仅作记录, 当前我正在尝试提取link节点以获取CSS文件的URL。

For the URL of your CSS files, this regexp should do the trick: 对于您的CSS文件的URL,此regexp应该可以解决问题:

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(). 对于DOM中的顶级元素,似乎必须使用filter()而不是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... 您可以查询jQuery对象...

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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