SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Member
    Join Date
    Mar 2006
    Posts
    6
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    adding a css property to a class in javascript

    Hey,
    I have several div elements with the same class. When my page loads i work out the dimensions of these divs based on various factors. Rather than getting each element by id or classname and setting each individual width and height i would like to set the width and height properties in the css class itself. I hoping this will improve the load time of the page.

    Anybody any ideas if this is possible? I need it to work in IE and FF.

    Thanks

  2. #2
    SitePoint Wizard
    Join Date
    Mar 2001
    Posts
    3,537
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Anybody any ideas if this is possible?
    Yes, it is.

  3. #3
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    simplest way is to create a style element and append it to the document head.
    Then append the selector and declaration to the style element-
    as element.stylesheet.cssText in IE and as a new textNode in the others.

    Something like this:
    Code:
    	str=' .myclassname{width:'+x+'px;height:'+y+'px}';
    
    	var pa= document.getElementsByTagName('head')[0];
    	var el= document.createElement('style');
    	el.type= 'text/css';
    	el.media= 'screen';
    // now you need to branch between IE or not IE-addEventListener should do: 
    
    	if(document.addEventListener){
    		el.appendChild(document.createTextNode(str));
    	}
    	else  el.styleSheet.cssText= str;
    	pa.appendChild(el);
    	return el;
    There are more complicated ways, involving editing an existing stylesheet directly, but they don't work in as many browsers as this method.

  4. #4
    SitePoint Member
    Join Date
    Mar 2006
    Posts
    6
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    thanks will try that


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •