如何用javascript改变css href =“”?

时间:2014-03-17 02:03:57

标签: javascript css

我想使用js更改css href。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org  /TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="ko" xml:lang="ko">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title> New Document </title>
    <link rel="stylesheet" href="u1.css" type="text/css" />
</head>

我必须修复上面的代码。

<link rel="stylesheet" href="u1.css" type="text/css" />

改为

<link rel="stylesheet" href="u2.css" type="text/css" />

我可以在head标签中更改css href吗? 有可能吗?

2 个答案:

答案 0 :(得分:9)

使用document.querySelectordocument.querySelectorAll

查询任何其他元素
document.querySelector("link[href='u1.css']").href = "u2.css";

或者,您也可以通过document.styleSheets访问它。

举个例子:

// Change [href] on first stylesheet to u2.css
document.styleSheets[0].href = "u2.css";

答案 1 :(得分:1)

您可以向元素添加ID属性,并使用javascript替换href属性。

var link = document.getElementById('yourid');
link.setAttribute('href', 'newhref');

价: change the href of a css link via jquery