开发者

Get contents from <link> (not <a>) tag

开发者 https://www.devze.com 2023-04-12 20:44 出处:网络
Hi I\'m trying to get contents of the link tag. So with: <link rel=\"stylesheet\" href=\"some.css\">

Hi I'm trying to get contents of the link tag. So with:

<link rel="stylesheet" href="some.css">

I want the contents of the file some.css in a string.

Tried:

document.getElementsByTagName('link')[0].firstChild.nodeValue; // fails
document.getElementsByTagName('link')[0].hasChildNodes(); // false

Any ideas? I don't want to use the styleSheet method (which only works in FF anyway) because it will strip out开发者_运维知识库 stuff like -moz-border-radius and such.

Thanks.


I think Daniel A. White is correct. Your best bet is to get the href of the stylesheet, then load the content via Ajax and parse it.

What are you trying to do exactly?


You can't get the contents of a file with only javascript. You'll need an ajax request to the server which opens the file and returns its contents.


To do this, you need to access the file via an ajax request.

So, with jQuery, something like this

$.ajax({
  url: "some.css",
  success: function(){
    //do something
  }
});

More details here: http://api.jquery.com/jQuery.ajax/

Note: this only works if the file making the request is on the same server as the file requested.


CSS rules offer a special API, but nothing like innerHTML.

This is as close as it gets:

var result = '';
var st = document.styleSheets[0].cssRules;
for (var i = 0; i < st.length; i++) {
    result += st[i].cssText;
}
console.log(result);

However, this will not respect whitespace, comments, erroneous rules, ...

And as usual, this is subject to Same Origin Policy.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号