I am trying to understand the behavior of style tags when used with innerHTML.
I did 3 experiments:
Style with existing rule, innerHTML inserts other selector rule
Result: both rules apply. Demo: http://jsfiddle.net/Tcy3B/
Style with existing rule, innerHTML inserts same selector 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 one. Demo: http://jsfiddle.net/Tcy3B/2/
Could anybody explain the logic? This looks totally random to me, sometimes the second rule is added to the first one, sometimes it is ignored, and sometimes it overwrites the first one.
Background: the idea is to build dynamic UIs that rely on css rather than JavaScript, as illustrated in this full text search example.
As an example, here is the code of 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;}";