Daburu
Daburu

Reputation: 117

Change style sheet using js

Hi I'm making my own website and I want to be able to change the style sheet and content of the page with js.

So I wrote this:

<head>
    <link id="style" rel="stylesheet" href="css/index.css">
</head>

<header>
    <ul id="nav">
        <li> <input id="home" onclick="home()" type="image" src="vzbt.png" widht="55" height="55"></li>
        <li> <button id="links" onclick="links()">Links</button> </li>
        <li> <button id="about" onclick="about()">About Me</button> </li>
        <li> <button id="music" onclick="music()">Music</button> </li>
        <li> <button id="contact" onclick="contact()">Contact</button> </li>
    </ul>
</header>

This is the js that I wrote so far

function links(){
    document.getElementById("style").setAttribute = ("href", links.css);
}

But it doesn't work, so I want to ask if someone can help me? Please.

Upvotes: 2

Views: 266

Answers (5)

Daburu
Daburu

Reputation: 117

I feel really stupid that I didn't figured it out sooner there was an error that "links" is not a function so I renamed it to "link" and surprise it works just fine but thanks to all of you for taking your time and trying to help.

Upvotes: 0

Kumar Aman
Kumar Aman

Reputation: 271

function links(){
  document.getElementById("style").href = path_Of_CSS_File;
}

You can also assign the value of href to the new value.

Upvotes: 0

Przemek
Przemek

Reputation: 3975

setAttribute is a function, not property (you try to assign a value to it with =).

function links(){
    document.getElementById("style").setAttribute("href", "css/links.css");
}

OR

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

Upvotes: 0

daddygames
daddygames

Reputation: 1928

Don't load any CSS into the page. On load of the page, determine which CSS and then use the following method to dynamically add the desired CSS to the page. You will need to store the chosen theme in localStorage and then use that on page load to determine the css file to load.

see: How to load up CSS files using Javascript?

Upvotes: 0

Ash
Ash

Reputation: 722

My guess is you should be doing it in following way:

function links(){
    document.getElementById("style").setAttribute("href", "css/links.css");
}

As links.css is not some js variable, you should put in inside " "

Upvotes: 1

Related Questions