I've got a chunk of CSS as a string, and I want to insert it into the DOM such that it only applies to elements in a particular container. Some tools, like Polymer, for example, rewrite CSS selectors so they only apply within a limited scope. How can I do something similar so that, when I insert this CSS into the DOM, it won't change all elements on the page?
To make it more concrete, imagine the following HTML and CSS from an external source:
<style>p { font-size: 20px; }</style>
<p>Boo.</p>
I want to insert these elements into a #container
element, but I don't want to change the font-size for all <p>
elements. I'd like to rewrite all the selectors inside that <style>
element so they only apply within #container
(p
-> #container p
, etc.). How?