Thursday, April 25, 2024
 Popular · Latest · Hot · Upcoming
133
rated 0 times [  134] [ 1]  / answers: 1 / hits: 17005  / 12 Years ago, thu, december 6, 2012, 12:00:00

I am trying to change the href of a link tag so that when a button is pressed a new style sheet is loaded.


function addcss()
{

var findlink = document.getElementsByTagName("link");
findlink.href = "stylesheetxhtml.css";
}


More From » html

 Answers
21

You can't set the href directly like that, because document.getElementsByTagName returns all the <link> tags (as a NodeList). If you're positive you only have one, use this:



var findlink = document.getElementsByTagName(link);
findlink[0].href = stylesheetxhtml.css;


If you have multiple <link> elements and want to target a specific one, give it an id and use document.getElementById:



var findlink = document.getElementsById(myLinkId);
findlink.href = stylesheetxhtml.css;


Finally, if you want to create a new <link> element, use document.createElement:



var newLink = document.createElement('link');
newLink.href = stylesheetxhtml.css;
document.getElementsByTagName(head)[0].appendChild(newlink);

[#81591] Tuesday, December 4, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tyemathewj

Total Points: 484
Total Questions: 107
Total Answers: 111

Location: Equatorial Guinea
Member since Sun, Feb 14, 2021
3 Years ago
;