jQuery and ASP.NET

July 22, 2009

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="http://www.w3.org/1999/xhtml">
<
head>
<
title></title>
<
link href="CSS/FloatDes.css" rel="stylesheet"
title="Float layout" type="text/css" />

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

</
body>
</
html>


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.



'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP 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 has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

6 Responses to "How to add a CSS Link programmatically using JavaScript"
  1. Jumler said...
    July 23, 2009 8:04 AM

    How to do it in an ASP.NET page?

  2. Anonymous said...
    July 23, 2009 10:08 PM

    @Jumler

    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.

  3. Suprotim Agarwal said...
    July 24, 2009 4:16 AM

    The HTMLLink class has made it easy to do it in ASP.NET. Check this post http://www.devcurry.com/2009/07/how-to-add-css-programmatically-to.html

  4. Anonymous said...
    January 14, 2011 2:29 PM

    shouldn't the line:
    "headtg.appendChild(link);"

    actually read:
    "headtg.appendChild(linktg);"

    Like this alot, thanks so much for posting!

    -AT

  5. Suprotim Agarwal said...
    January 15, 2011 6:38 AM

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

  6. Anonymous said...
    January 28, 2012 2:42 PM

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

 

Copyright © 2009-2011 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions