使用javascript更改链接标记的href

时间:2012-12-06 00:54:47

标签: javascript html css href link-tag

您好我正在尝试更改链接标记的href,以便在按下按钮时加载新的样式表。 这是我到目前为止 -

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

任何帮助非常感谢谢谢

1 个答案:

答案 0 :(得分:6)

您不能直接设置href,因为document.getElementsByTagName会返回所有<link>标记(作为NodeList)。如果你是肯定的,你只有一个,请使用:

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

如果您有多个<link>元素并希望定位特定元素,请为其指定ID并使用document.getElementById

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

最后,如果您要创建新的<link>元素,请使用document.createElement

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