How to add a CSS Link programmatically using JavaScript

In one of my earlier posts, I demonstrated how to Programmatically Retrieve StyleSheet Url’s Referenced in your Page using JavaScript. In this post, here’s a piece of JavaScript code that demonstrates how you can programmatically reference a CSS link on a page.

<html xmlns="">
link href="CSS/FloatDes.css" rel="stylesheet"
title="Float layout" type="text/css" />

script type="text/javascript">
addCSS() {
var headtg = document.getElementsByTagName('head')[0];
if (!headtg) {
var linktg = document.createElement('link');
linktg.type = 'text/css';
linktg.rel = 'stylesheet';
linktg.href = 'CSS/RoundCorners.css';
linktg.title = 'Rounded Corners';
body onload="addCSS()">


The code shown above creates a link element(with properties) and appends it as a child to the &lt;head&gt; section. You can use this technique to let users choose styles and change the appearance of the page.

Will you give this article a +1 ? Thanks in advance

About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal


Jumler said...

How to do it in an ASP.NET page?

Anonymous said...


I would imagine, but feel free to correct me, server technology ( such as ASP or JSP ) shouldn't have any effect on it.

Essentially, as long as it is present in the browser, it will have HEAD element and thus the above JS will work.

Suprotim Agarwal said...

The HTMLLink class has made it easy to do it in ASP.NET. Check this post

Anonymous said...

shouldn't the line:

actually read:

Like this alot, thanks so much for posting!


Suprotim Agarwal said...

Yes that's a typo and thanks for pointing it out. The code has been updated!

Anonymous said...

How can I make a link to get back to the original CSS?

Wjs Com said...

You can also use wjs library for that :

wjs.use('CssLink', 'yourcss.css');