Reputation: 21062
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.
Upvotes: 3
Views: 782
Reputation: 286
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.
Upvotes: 3
Reputation: 286
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]);
}
Upvotes: 1
Reputation: 4483
You can just query the jQuery object for it...
var sHtmlString = ....;
var oDom = $(sHtmlString);
oDom.find("head > link");
Upvotes: 0