Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
1
rated 0 times [  5] [ 4]  / answers: 1 / hits: 19518  / 14 Years ago, fri, march 26, 2010, 12:00:00

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


More From » html

 Answers
58

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.


[#97240] Monday, March 22, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ryanulyssesb

Total Points: 91
Total Questions: 105
Total Answers: 102

Location: England
Member since Tue, Sep 8, 2020
4 Years ago
ryanulyssesb questions
Sat, Mar 20, 21, 00:00, 3 Years ago
Mon, Sep 14, 20, 00:00, 4 Years ago
Mon, Mar 9, 20, 00:00, 4 Years ago
Sun, Jul 7, 19, 00:00, 5 Years ago
;