4

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"; }

0

2 Answers 2

10

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);
Sign up to request clarification or add additional context in comments.

3 Comments

Ah Thank you, just that little bit off lol. so if i had more than one link tag I would have to look for the link with the href I wanted to change. Or would I add change the number 0? sorry quite new to javascript. Don't worry if your busy. Thanks for your help
It's easier to just give it an id, instead of looping through all link elements and checking the hrefs.
Awesome thanks, one more question if you don't mind. How would I get it to go back up to the top of the page once the button was pressed. I tried the function "window.location.reload()" but that obviously just reloaded the page without the link change
0

Man, the most simple way is: Just type this: document.querySelector(".search").setAttribute("href","https://www.google.com/");

Now Make your button do this on click!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.