views:

1869

answers:

5

I have below code to insert a style into DOM (there is a use case for injecting style into DOM so please don't ask why or say to load the css in .css file).

<script type="text/javascript">
window.onload = function()
{
    var bmstyle = document.createElement('style');
    bmstyle.setAttribute('type', 'text/css');
    var styleStr = "#test-div {background:#FFF;border:2px solid #315300;";
    bmstyle.innerHTML = styleStr;
    document.body.appendChild(bmstyle);
}

</script>

If I run in Firefox, it works fine. But I got this error in Google Chrome:

Line bmstyle.innerHTML = styleStr;
Uncaught Error: NO_MODIFICATION_ALLOWED_ERR: DOM Exception 7

Does anyone have a fix? Thanks

+4  A: 

I think it's because you are using innerHTML when everywhere else you are using XML syntax. Try:

bmstyle.nodeValue = styleStr;

Suggestion 2:

It might also be because you are trying to set the innerHTML of a an element not yet in the HTML DOM. If that's the case, my first suggestion should still hold up, or you can go with:

document.body.appendChild(bmstyle);
bmstyle.innerHTML = styleStr;

I'm not sure if you'd need a line inbetween to reclaim the element or if the bmstyle would still point to it.

Anthony
I should mention that since the DOM in this case is an HTML DOM, it shouldn't matter. But Chrome may be pissy when you don't set up the DOM Element variable explicitly as HTML.
Anthony
I used your suggestion 2 and it still has error. I used suggestion 1 with nodeValue, it has no error but the style tag has nothing in it (btw, I corrected to add } at the end). Should I insert in header instead and how?
HP
@Anthony: Thanks for this! Very helpful
Senica Gonzalez
A: 

It could be because it's invalid to put <style> elements inside the body, but to be honest I would be surprised

Gareth
A: 

I had this problem too, try: "bmstyle.value = styleStr;"

Briandotcom0
A: 

As seen on

http://www.karthikeyanc.com/blog/index.php/2010/06/chrome-error-no_modification_allowed_err-dom-exception-7/

try using

<f:view xmlns:f="http://java.sun.com/jsf/core" contentType="text/html" />

DiS