Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Style innerHTML

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;}";
like image 373
Christophe Avatar asked Sep 11 '13 21:09

Christophe


People also ask

How do you add a style to innerHTML?

To append code using the innerHTML attribute, first choose the element (div) that you want to append to. InnerHTML also allows you to include strings with the code enclosed as strings using the += operator. As we will see in this article, we will learn how to change the text or the HTML on a page.

What is innerHTML?

The Element property innerHTML gets or sets the HTML or XML markup contained within the element. To insert the HTML into the document rather than replace the contents of an element, use the method insertAdjacentHTML() .

Why you shouldn't use innerHTML?

The use of innerHTML creates a potential security risk for your website. Malicious users can use cross-site scripting (XSS) to add malicious client-side scripts that steal private user information stored in session cookies. You can read the MDN documentation on innerHTML .

Is innerHTML a string?

The innerHTML property takes a string that specifies a valid combination of text and elements. When the innerHTML property is set, the given string completely replaces the existing content of the object.


1 Answers

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.

like image 108
dig Avatar answered Oct 03 '22 07:10

dig