Reputation: 1
How do I grab all hrefs from a list with jquery or javascript and add it to header as "text/css"?
List:
<ul class="active">
<li><a href="/path/to/link1">link1</a></li>
<li><a href="/path/to/link2">link2</a></li>
<li><a href="/path/to/link3">link3</a></li>
</ul>
Desired result:
<head>
[...]
<link rel="stylesheet" type="text/css" href="path/to/link1.css">
<link rel="stylesheet" type="text/css" href="path/to/link2.css">
<link rel="stylesheet" type="text/css" href="path/to/link3.css">
</head>
I think there is a way to do this with something like this:
<script>
var hrefs = [];
jQuery('.active')
.find('a[href]')
.each(function() {
hrefs.push(this.href);
})
;
var code = '<link rel=\"stylesheet\" type=\"text/css\" href=\"' + hrefs + '\.css" />';
var temp = document.createElement('div');
temp.innerHTML = code;
var head = document.head;
while (temp.firstChild) {
head.appendChild(temp.firstChild);
}
</script>
Could anybody help me?
Upvotes: 0
Views: 87
Reputation: 3510
jQuery:
$('.active a[href]').each(function() {
var $style = $('<link/>').attr({"rel":"stylesheet","type":"text/css","href":this.href});
$('head').append($style)
});
For each anchor create a new <link>
and pass the appropriate attibutues to it. Then append them to the head.
https://jsfiddle.net/dufn7vyt/1/
javascript:
var anchors = document.querySelectorAll('.active a[href]');
var head = document.getElementsByTagName('head')[0];
for (i = 0; i < anchors.length; ++i) {
var link = document.createElement('link');
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = anchors[i].href;
head.appendChild(link);
}
https://jsfiddle.net/dufn7vyt/3/
Support for querySelectorAll
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll
Upvotes: 3