Style innerHTML

23,235

As a crude intuitive rule-of-thumb, it may be useful to note that innerHTML is intended to work with HTML, but you're applying it on CSS. You might expect to encounter similar "funny" problems if you tried to modify script elements using innerHTML.

A better interface for dynamically modifying the styling rulesets would be document.styleSheets. The W3 Consortium has a useful overview on this here.

Share:
23,235
Christophe
Author by

Christophe

SharePoint consultant with a focus on the user side: business analysis, process mapping information architecture workflows (SharePoint Designer) client side solutions My free client side solutions are published here: http://usermanagedsolutions.com/SharePoint-User-Toolkit/ On twitter: https://twitter.com/Path2SharePoint https://twitter.com/UserManaged My company is a Microsoft Partner for Office 365.

Updated on April 03, 2020

Comments

  • Christophe
    Christophe about 4 years

    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;}";
    
  • Erik Christianson
    Erik Christianson over 10 years
    Agreed. But I was commenting about his third example. What you have in the style tags originally seems to be preserved, but in the third example, when you have no styles there originally, and only add them one at a time it overwrites them unless you use +=. jsfiddle.net/mtr4b/1
  • Vicentiu B
    Vicentiu B over 10 years
    The styles that are already in there are already applied by the browser.
  • Christophe
    Christophe over 10 years
    the style element is html. The link you're referencing (+1 for that) uses methods such as innerHTML and getElementById on style elements.