views:

52

answers:

2

Hi. I am building a javascript widget and i need to add my widget css and js files dynamicly to the client page.

I am doing this for now:

    var css = document.createElement('link');
   css.setAttribute('rel', 'stylesheet');
   css.setAttribute('href', 'css path');
   document.getElementById('test').appendChild(css);
   alert(document.getElementById('test').innerHTML);

But it does not add the element to the dom. The alert shows correctly.

What i am missing?

EDIT1:

Here is the updated code: (note that this is only a test page).

<html>
    <head>

    </head>
    <body>
        <div id="test">
            test
        </div>

        <script type="text/javascript">


    var css = document.createElement('link');
    css.setAttribute('rel', 'stylesheet');
    css.setAttribute("type", "text/css");
    css.setAttribute('href', 'path');
    var header  = document.getElementsByTagName("head")[0];
    header.appendChild(css);
    alert(header.innerHTML);

        </script>  
    </body>
</html>

header.InnerHtml appears correct but nothing is added to the page.

+3  A: 

have you tried to append the css into the <head> section ?

var css = document.createElement('link');
   css.setAttribute('rel', 'stylesheet');
   css.setAttribute('href', 'css path');
   document.getElementsByTagName('head')[0].appendChild(css);
Fabrizio Calderan
+1 - CSS includes need to be declared in the "head" element of the document. It isn't valid to include it anywhere else.
Sohnee
+2  A: 

I think you need to attach it to the of your html, not simply the document:

var css = document.createElement('link');
css.setAttribute('rel', 'stylesheet');
css.setAttribute("type", "text/css");
css.setAttribute('href', 'css path');
var header   = document.getElementsByTagName("head")[0];
header.appendChild(css);

Hope this helps :)

mrjames
It still doesn´t work. The innerHTML of the header element is correct but nothing is added to the page. I will post the updated code at first post.
Popovich88