Changing the href of a link tag using javascript

随声附和 提交于 2019-11-28 01:35:32

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!