3

I'm currently trying to make a series of buttons that the user of my site can click on in order to change between different CSS3 files, which will change certain effects. In order to accomplish this goal, I need some way of accessing the

href="example1.css"

tag in my HTML, and changing it to

href="example2.css" 

using JavaScript or HTML.

ProgramFOX
  • 6,131
  • 11
  • 45
  • 51
CloudTwoNJ
  • 65
  • 2
  • 8
  • You can do this two ways: using vanilla js, or jquery. This question was asked and answered here: http://stackoverflow.com/questions/11522545/how-to-change-the-css-stylesheet-dynamically-for-a-website-being-viewed – SeanOlson May 22 '15 at 16:50

2 Answers2

9

Assign an id to your link. Fetch it in JS by its id and change the href attribute.

<link rel="stylesheet" type="text/css" href="example1.css" id="lnk"/>

In JS:

var link = document.getElementsById("lnk"); //Fetch the link by its ID
link.setAttribute("href", "example2.css"); //Change its href attribute

You can also do it without an id.

document.querySelector("link[href='example1.css']").href = "example2.css";
Zee
  • 8,420
  • 5
  • 36
  • 58
  • Spelling mistake. `getElementsById` should be `getElementById` since really, the `Id` should be unique, and hence there should be only one of it. – Andrei Bazanov Nov 13 '19 at 15:15
0

not

var link = document.getElementsById("lnk"); //Fetch the link by its ID 

but

link = document.getElementById("lnk"); 

The ID is ONE, getElementsById - is array

CroMagnon
  • 1,218
  • 7
  • 20
  • 32
Dudar Mykola
  • 89
  • 1
  • 2