Sarta
Sarta

Reputation: 139

How to have javascript modify css link based on page name?

I want the below javascript to update the specific css link bootstrap.min.js if the page is named mypage.html.
How would I do that?

<html>
  <head>

  <link rel="stylesheet" type="text/css" href="/css/bootstrap377.min.css"/>
  <link rel="stylesheet" type="text/css" href="/css/some_other_stylesheet.css"/>

  <script type="text/javascript">
    var filename = location.href.split("/").slice(-1); 

    if (filename == "mypage.html") {
      HOW DO I DO THIS:  update the above stylesheet link to be bootstrap400.min.css (or should this script be before the css link?)
    }
  </script>


  </head>
  <body>
    this is a test
  </body>
</html>

Upvotes: 1

Views: 172

Answers (1)

GOTO 0
GOTO 0

Reputation: 47702

Use document.querySelector to get a reference to the link element, then change the href property the usual way.

var filename = location.href.split("/").slice(-1); 

if (filename == "mypage.html") {
  var link = document.querySelector("link[href='/css/bootstrap377.min.css']");
  link.href = "/css/bootstrap400.min.css";
}

Upvotes: 1

Related Questions