I am trying to import an svg
, which has some paths with class .desired
,
.desired {
fill: red;
background: red;
cursor: pointer;
}
I want to apply the styles on these elements with that class. I don’t know why it doesn’t work.
If I put the <svg>
directly in my template it works, but that’s what I want to avoid since I can have very large .
how can I fix it?
Expected behaviour
Note: I want to avoid putting long directly in the html template.
var desiredElements = document.querySelectorAll('.desired');
desiredElements.forEach(function (element) {
element.addEventListener('click', function () {
console.log('"desired"');
});
});
.desired {
fill: red;
background: red;
cursor: pointer;
}
<object
type="image/svg+xml"
data="https://svgshare.com/i/xRE.svg"
class="logo"
>
</object>
2
Answers
<object>
elements, like<iframe>
s, load external media in a self-contained document.The stylesheet belonging to the HTML document does not get transferred through the
<object>
to the SVG.You’d need to attach the CSS to the SVG itself for it to apply.
(As you observed, if you used an
<svg>
element directly in your HTML document, then the stylesheet would also apply to it).The svg’s cannot be modified if it’s in an object element. I know, its frustrating. But there is a way. Try it and thank me later 🙂