I am trying to understand the behavior of style tags when used with innerHTML.
I did 3 experiments:
Style with an existing rule, innerHTML inserts another selection rule
Result: Both rules apply. Demo: http://jsfiddle.net/Tcy3B/
A style with an existing rule, innerHTML inserts the same selection rule
Result: the new rule is ignored. Demo: http://jsfiddle.net/Tcy3B/1/
Empty style, innerHTML inserts a rule, then another innerHTML inserts another rule
Result: The second rule overwrites the first. Demo: http://jsfiddle.net/Tcy3B/2/
Can anyone explain the logic? It looks completely random for me, sometimes the second rule is added to the first, sometimes it is ignored, and sometimes it overwrites the first.
Background : The idea is to create dynamic user interfaces that rely on css rather than JavaScript, as shown in this full-text search example .
As an example, here is the code for the second demo:
HTML:
<style type="text/css"> .red {color:red;} </style> <div class="red">red</div> <div class="blue">blue</div>
JavaScript:
var st=document.getElementsByTagName("style")[0]; st.innerHTML=".red {color:blue;}";
source share