InnerHTML style

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;}"; 
+6
source share
2 answers

As a rough, intuitive thumb rule, it can be helpful to note that innerHTML designed to work with HTML, but you apply it in CSS. You might run into similar “funny” problems if you try to modify script elements using innerHTML .

The best interface for dynamically changing stylesheet sets is document.styleSheets . The W3 Consortium has a helpful overview on this issue http://www.w3.org/wiki/Dynamic_style_-_manipulating_CSS_with_JavaScript .

+3
source

This is pretty interesting.

It looks like when you already have a style already loaded into the <style></style> tags, it saves it after writing the <style> tag to the .innerHTML tag. However, every time you write in .innerHTML , it overwrites it all. if in the third example you use += as shown below, it should add both styles:

 var st=document.getElementsByTagName("style")[0]; st.innerHTML = ".red {color:red;}"; st.innerHTML += ".blue {color:blue;}"; 
0
source

Source: https://habr.com/ru/post/953655/


All Articles