I want to change css href using js.
<!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>
I have to fix above code.
<link rel="stylesheet" href="u1.css" type="text/css" />
change into
<link rel="stylesheet" href="u2.css" type="text/css" />
Can I change css href in head tag? Is it possible?
Query for it like you would any other element using document.querySelector
or document.querySelectorAll
.
document.querySelector("link[href='u1.css']").href = "u2.css";
Alternatively, you could also access it via document.styleSheets
as well.
As an example:
// Change [href] on first stylesheet to u2.css
document.styleSheets[0].href = "u2.css";
You can add ID attribute to the element and replace the href attribute with javascript.
var link = document.getElementById('yourid');
link.setAttribute('href', 'newhref');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With