www.webdeveloper.com
Results 1 to 4 of 4

Thread: importing css using js

  1. #1
    Join Date
    Nov 2007
    Posts
    17

    importing css using js

    i have tried a bunch of methods a few bellow:

    Code:
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>
    <link id="myid" rel="stylesheet" type="text/css" media="screen" />
    <script type="text/javascript">
      sigh=document.getElementById('myid');
      sigh.setAttribute('href', 'css/bg.css');
    </script>
    
    </head>
    aswell as a slightly more complex one.

    Code:
    function css(source) {
    	create = document.createElement('link');
    	create.setAttribute('rel' , 'stylesheet');
    	create.setAttribute('type' , 'text/css');
    	create.setAttribute('href' , source);
    	document.childNodes[0].appendChild(create); ;
    }
    
    if (!window.ie) {
    	css('/css/bg.css');
    }
    i have tried a massive amount of different scripts. just cant seem to get it right im not sure if its me or what.

    thanks for looking
    -nick

  2. #2
    Join Date
    Apr 2003
    Location
    Netherlands
    Posts
    21,654
    Code:
    document.getElementsByTagName('head')[0].appendChild(create);
    At least 98% of internet users' DNA is identical to that of chimpanzees

  3. #3
    Join Date
    Nov 2007
    Posts
    17
    that did not seem to work. i just wanted to inject a new tag into head based on browser. i have tried this code here and it failed.

    Code:
    <!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">
    
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>lol</title>
    <script type="text/javascript">
    	create = document.createElement('link');
    	create.setAttribute('rel' , 'stylesheet');
    	create.setAttribute('type' , 'text/css');
    	create.setAttribute('href' , source);
    	document.getElementsByTagName('head')[0].appendChild(create);
    </script>
    
    </head>
    
    <body>
    lol
    </body>
    
    </html>
    i also tried to remove the xhtml tag aswell as placing the script into the body of the document. nothing seemed to work.

    -nick

  4. #4
    Join Date
    Apr 2003
    Location
    Netherlands
    Posts
    21,654
    The code works if the function is called after the head has loaded and the path to the css is correct.
    At least 98% of internet users' DNA is identical to that of chimpanzees

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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



Recent Articles