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

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?

Answers:

Answer

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";
Answer

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.