Skip to content
Advertisement

how to change `href` in `link` by javascript

I would like to change target on link tag with my css. I would like to do this with javascript. It should be when I click on button. I have html file

<!DOCTYPE html>
<html lang="pl">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">

    <link rel="stylesheet" href="css/general.css">
    <link id="my_css" rel="stylesheet" href="css/normal_mode.css">


</head>
<body id="my_body">
...

I have javascript file

function dark_mode() 
    {
        if(document.getElementById("my_css").href == "css/normal_mode.css")
        {
            document.getElementById("my_body").className = ""; 
            document.getElementById("my_name").className = "";
            document.getElementById("my_css").href = "new.css";
...

Advertisement

Answer

Your approach is incorrect, or not practical. What you need to do is to load CSS for both themes and change the body theme data or class.

.theme-dark {
  --bg: black;
  --text: white;
}

.theme-light {
    --bg: white;
    --text: black;
}

in JS

document.querySelector(".switch-theme").addEventListener("click", () => {
   document.body.classList.toggle("theme-dark");
   document.body.classList.toggle("theme-light");
})
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement