Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change css href="" using javascript? [duplicate]

Tags:

javascript

css

I want to change css href using js.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org  /TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="ko" xml:lang="ko">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title> New Document </title>
    <link rel="stylesheet" href="u1.css" type="text/css" />
</head>

I have to fix above code.

<link rel="stylesheet" href="u1.css" type="text/css" />

change into

<link rel="stylesheet" href="u2.css" type="text/css" />

Can I change css href in head tag? Is it possible?

like image 459
user2738656 Avatar asked Mar 17 '14 02:03

user2738656


2 Answers

Query for it like you would any other element using document.querySelector or document.querySelectorAll.

document.querySelector("link[href='u1.css']").href = "u2.css";

Alternatively, you could also access it via document.styleSheets as well.

As an example:

// Change [href] on first stylesheet to u2.css
document.styleSheets[0].href = "u2.css";
like image 162
Sampson Avatar answered Sep 22 '22 07:09

Sampson


You can add ID attribute to the element and replace the href attribute with javascript.

var link = document.getElementById('yourid');
link.setAttribute('href', 'newhref');

Ref: change the href of a css link via jquery

like image 40
Iqbal Fauzi Avatar answered Sep 19 '22 07:09

Iqbal Fauzi