How to use CSSStyleSheet.insertRule () correctly?

I can’t understand where I made a mistake here: /. When I run this code, all I get is an empty element. I can't seem to get the insertRule method to do anything (not even cause errors). Did I miss something?

<!DOCTYPE html> <html> <head> <title>Test</title> </head> <body> <script> var sheet = (function() { // Create the <style> tag var style = document.createElement("style"); // WebKit hack style.appendChild(document.createTextNode("")); // Add the <style> element to the page document.head.appendChild(style); return style.sheet; })(); sheet.insertRule("\ #gridContainer {\ width: 100%;\ height: 100%;\ }\ ", 0); </script> </body> </html> 
+6
source share
2 answers

This is a bit confusing, but your code really works, you just cannot see the inserted rules in the returned XML tree.

To make sure your code works, there are two tests you can perform:

 var style = (function() { // Create the <style> tag var style = document.createElement("style"); // WebKit hack style.appendChild(document.createTextNode("")); // Add the <style> element to the page document.head.appendChild(style); console.log(style.sheet.cssRules); // length is 0, and no rules return style; })(); style.sheet.insertRule('.foo{color:red;}', 0); console.log(style.sheet.cssRules); // length is 1, rule added 
 <p class="foo"> I am some text </p> 

Run the above snippet and you will see that the CSS rule applies. And the cssRules property also changes in the console.

This is often noted when browser extensions generate custom stylesheets added to the DOM, and when they are debugged, they appear as empty stylesheets in the inspector.

+8
source

This version is based on the answer from Awal and Totally Pwn CSS with Javascript from the web archive . The id parameter is useful for accessing the StyleSheet style using getElementById, and the media parameter is optional and deactivates the screen. I return styleSheet.sheet , these are just my preferences.

 function createStyleSheet (id, media) { var el = document.createElement('style'); // WebKit hack el.appendChild(document.createTextNode('')); el.type = 'text/css'; el.rel = 'stylesheet'; el.media = media || 'screen'; el.id = id; document.head.appendChild(el); return el.sheet; } 
+1
source

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


All Articles