4

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.

1
  • You can do this two ways: using vanilla js, or jquery. This question was asked and answered here: stackoverflow.com/questions/11522545/… Commented May 22, 2015 at 16:50

2 Answers 2

10

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";
Sign up to request clarification or add additional context in comments.

1 Comment

Spelling mistake. getElementsById should be getElementById since really, the Id should be unique, and hence there should be only one of it.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.