skip to Main Content

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?

enter image description here

Expected behaviour

enter image description here

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


  1. <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).

    Login or Signup to reply.
  2. 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 🙂

    <script>
      // Wait for the SVG to load
      var logoObject = document.getElementById('logoObject');
    
      logoObject.addEventListener('load', function () {
        // Get the SVG document inside the <object> element
        var svgDoc = logoObject.contentDocument;
        
        // Check if the SVG document is loaded successfully
        if (svgDoc) {
          // Find and style the elements with the "desired" class
          var desiredElements = svgDoc.querySelectorAll('.desired');
    
          desiredElements.forEach(function (element) {
            element.style.fill = 'red';
            element.style.background = 'red';
            element.style.cursor = 'pointer';
    
            // You can also add event listeners to these elements
            element.addEventListener('click', function () {
              console.log('"desired"');
            });
          });
        }
      });
    </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search