D
D
Dmitry2015-10-25 12:46:48
css
Dmitry, 2015-10-25 12:46:48

How to change css file with JS and return original value?

Good afternoon!
I'm just starting to learn JavaScript and I have a question. It is necessary to change the href attribute in the link tag on button click to replace the css file.
Wrote a function:

function changeCss() {
document.getElementById("styleBright").href="css/style.css";
}

Connected to the button using onclick. Now the question arose, how to check the value of the href attribute of the link tag and, depending on what it is worth changing the href between two files when you click on the same button?
The option with if is spinning in my head, but I don’t understand what to check it for.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Andrey Khokhlov, 2015-10-25
@Lostmain

Well, take the current value of the attribute and, depending on it, do what you need.

var link = document.getElementById("styleBright"),
    href = link.getAttribute('href');

if(href == 'css/style.css') {
    // do something
} else if (href == 'css/style2.css') {
    // do something
}

V
VisualIdeas, 2015-10-25
@VisualIdeas

Maybe I'm wrong, but maybe this:

if (document.getElementById("styleBright").href==="css/style.css") {
//что-то делаем
} else {
//чтото делаем, например:
document.getElementById("styleBright").href="css/style.css";
}

PS: I would put document.getElementById("styleBright") into a variable naturally

D
Dmitry, 2015-10-25
@Lostmain

Thanks to all! I went the other way:

function changeCss() {
    document.getElementById("styleBright").href="css/style.css";
    document.getElementById("switcher").value="Back to default";
    document.getElementById("switcher").onclick = changeCssToDefault;
  }
  
  function changeCssToDefault() {
    document.getElementById("styleBright").href="css/main.css";
    document.getElementById("switcher").value="Switch the light";
    document.getElementById("switcher").onclick = changeCss;
  }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question