I'm importing an svg from file using the <object>
element
<object data="img/icons/some-svg.svg" type="image/svg xml"></object>
From the inspect element tool it's hierarchy appears as follows in the browser
<object data="img/icons/some-svg.svg" type="image/svg xml">
#document
<svg ...>
...
</svg>
</object>
As I want to change the color of the svg how do I access the encapsulated svg component in the object element?
CodePudding user response:
svg {
fill: #ff0000;
}
use this css rule to change the color
CodePudding user response:
Here's how you insert a style into a document. The rect element has no colour defined in markup, the green colour comes from the javascript injected style rule.
document.styleSheets[0].insertRule('rect { fill: green; }', 0);
<svg viewBox="0 0 220 100" xmlns="http://www.w3.org/2000/svg"><rect width="100" height="100"/></svg>
So now we know how to do that how do we use it with an object tag. Well we need to get the object tag. You could either give it an id and get it by its id or try to find it in the DOM e.g.
let o = document.getElementsByTagName('object')[0];
Then you get its contentDocument i.e.
let doc = o.contentDocument;
and you can use that to insert the style as demonstrated above. I.e.
doc.styleSheets[0].insertRule('rect { fill: green; }', 0);
Unfortunately I can't demonstrate this from start to finish because the contentDocument of a data url is null.