How to Use JavaScript to Change a Cascading Style Sheet (CSS) Dynamically

Posted on 2008-10-23
Last Modified: 2011-10-19
Hi Experts, i found a very code example in the internet on how to change the stylesheete in java script using multiple css, i attached my code.
there are 2 problems with this code:
1- in the example i am using cookies to save the user selection but its not working, in each page the style return to its default even if the user choose another style? is something wrong with the javascripts functions?

2- i am getting an error in the internet explorer for the javascript
Error: '2' is null or not an object
and this error belong to this function
""" get_cookie ( cookie_name ) """  for this line "" return decodeURIComponent ( cookie_value[2] ) ""

Can you please help me solving this problem? coz i am still cant understand cookies

Thank you.    
Question by:AZZA-KHAMEES
  • 4
  • 2

Expert Comment

ID: 22784975
Hi! Could you please post the code?

Author Comment

ID: 22785021
i attached the example

Expert Comment

ID: 22786083
Ok, the javascript error is the showstopper. I guess cookie_value is no array :-)

Replace the function:
function get_cookie ( cookie_name )



    var cookie_string = document.cookie ;

    if (cookie_string.length != 0) {

        var cookie_value = cookie_string.match (

                        '(^|;)[\s]*' +

                        cookie_name +

                        '=([^;]*)' );

        return decodeURIComponent ( cookie_value) ;


    return '' ;


Open in new window

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.


Accepted Solution

bluV11t earned 500 total points
ID: 22786150
In fact, replace the entire <script></script> block with this:

<script language="javascript">

var style_cookie_name = "style" ;

var style_cookie_duration = 30 ;

function switch_style ( css_title )


  var i, link_tag ;

  for (i = 0, link_tag = document.getElementsByTagName("link") ;

    i < link_tag.length ; i++ ) {

    if ((link_tag[i].rel.indexOf( "stylesheet" ) != -1) &&

      link_tag[i].title) {

      link_tag[i].disabled = true ;

      if (link_tag[i].title == css_title) {

        link_tag[i].disabled = false ;



    createCookie( style_cookie_name, css_title,

      style_cookie_duration );



function set_style_from_cookie()


  var css_title = readCookie( style_cookie_name );

  if (css_title.length) {

    switch_style( css_title );



function createCookie(name,value,days) {

	if (days) {

		var date = new Date();


		var expires = "; expires="+date.toGMTString();


	else var expires = "";

	document.cookie = style_cookie_name+"="+value+expires+"; path=/";


function readCookie(name) {

	var nameEQ = name + "=";

	var ca = document.cookie.split(';');

	for(var i=0;i < ca.length;i++) {

		var c = ca[i];

		while (c.charAt(0)==' ') c = c.substring(1,c.length);

		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);


	return null;




Open in new window

LVL 44

Expert Comment

ID: 22792210
generally speaking, javascript will NOT allow you to access the contents of the HEAD of a document.  Once you realize it is only BODY accessible, then you can figure out what you need to do to get it to work.

Expert Comment

ID: 22793927

Author Closing Comment

ID: 31509149
Thank you, its really worked Thank you bluV11t :)

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Suggested Solutions

Browsers only know CSS so your awesome SASS code needs to be translated into normal CSS. Here I'll try to explain what you should aim for in order to take full advantage of SASS.
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
In this tutorial viewers will learn how to position items using CSS's three positioning types Create a new HTML document with an internal stylesheet.: Create another div in CSS and name it Absolute : Type "position:absolute;" and "top:10px; left:50p…
In this tutorial viewers will learn how to style a corner ribbon overlay for an image using CSS Create a new class by typing ".Ribbon":  Define the class' "display:" as "inline-block": Define its "position:" as "relative": Define its "overflow:" as …

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now