简体   繁体   中英

Changing the href of a link tag using JavaScript

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

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);

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM