Reputation: 668
Let me start by saying im not 100% the way Im handling this is correct, but anyway..
I am loading HTML out of a file, into a string - and placing that string inside of a jquery object.
My HTML (example):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
...
<link href="template.css" rel="stylesheet" type="text/css" />
</head>
<body>
<img src="img.png"/>
...
</body>
</html>
The above is in a variable called htmlstr:
var htmlstr = theFunctionThatLoadsMyHTMLString();
$html = $(htmlstr);
Now, im going through the HTML and attempting to make some changes before I put it into an iframe.
This works perfectly fine for images:
$html.find("img").each(function(){
// do something
});
But, when I try to access the LINK tag (to change the css href) it doesn't find "link".
$html.find("link").each(function(){
// do something
});
To attempt to debug the problem, I wrote this code:
$html.find('*').each(function(index){
addline(index+': '+this.tagName+'');
});
It prints out the HTML tag found for each element (addline is a function that does this). This is what I get:
0: IMG
1: DIV
2: DIV
....
So it appears as if maybe its starting inside BODY for some reason, and ignoring the header?
What am I doing wrong here?
Im not gonna lie, Im not 100% sure how the $('code here') works in jQuery.. flying kind of blind.
Upvotes: 1
Views: 134
Reputation: 1828
Reproduced the problem in a JSFiddle and found that you can actually select the link if you know its position in the array. So, given that is is a fixed HTML, you could use that to find the link. However, I couldn't use any selector to find it, which is weird...
If you plan on using this, you should test it for crossbrowser issues, since all browser might not parse the head the same.
Upvotes: 0
Reputation: 51052
There may be a browser-specific effect here. The jQuery docs say
When passing in complex HTML, some browsers may not generate a DOM that exactly replicates the HTML source provided. As mentioned, we use the browser's .innerHTML property to parse the passed HTML and insert it into the current document. During this process, some browsers filter out certain elements such as
<html>
,<title>
, or<head>
elements. As a result, the elements inserted may not be representative of the original string passed.
Upvotes: 1