title: Style innerHTML
body: <p>I am trying to understand the behavior of style tags when used with innerHTML.</p>
  
  <p>I did 3 experiments:</p>
  
  <p><strong>Style with existing rule, innerHTML inserts other selector rule</strong></p>
  
  <p>Result: both rules apply. Demo: <a href="http://jsfiddle.net/Tcy3B/" rel="noreferrer">http://jsfiddle.net/Tcy3B/</a></p>
  
  <p><strong>Style with existing rule, innerHTML inserts same selector rule</strong></p>
  
  <p>Result: the new rule is ignored. Demo: <a href="http://jsfiddle.net/Tcy3B/1/" rel="noreferrer">http://jsfiddle.net/Tcy3B/1/</a></p>
  
  <p><strong>Empty style, innerHTML inserts a rule, then another innerHTML inserts another rule</strong></p>
  
  <p>Result: the second rule overwrites the first one. Demo: <a href="http://jsfiddle.net/Tcy3B/2/" rel="noreferrer">http://jsfiddle.net/Tcy3B/2/</a></p>
  
  <p>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.</p>
  
  <p><strong>Background</strong>: the idea is to build dynamic UIs that rely on css rather than JavaScript, as illustrated in this <a href="http://redotheweb.com/2013/05/15/client-side-full-text-search-in-css.html" rel="noreferrer">full text search example</a>.</p>
  
  <p>As an example, here is the code of the second demo:</p>
  
  <p>html:</p>
  
  <pre><code>&lt;style type="text/css"&gt;
    .red {color:red;}
  &lt;/style&gt;
  &lt;div class="red"&gt;red&lt;/div&gt;
  &lt;div class="blue"&gt;blue&lt;/div&gt;
  </code></pre>
  
  <p>JavaScript:</p>
  
  <pre><code>var st=document.getElementsByTagName("style")[0];
  st.innerHTML=".red {color:blue;}";
  </code></pre>