0

I have a svg file that contains some css classes in this format

  <style type="text/css" id="style1">
    <![CDATA[
      .fill1 {fill:#D2D3D5}
      .fill2 {fill:#A9ABAE}
      .fill3 {fill:#96989A}
    ]]>
  </style>

The svg file is displayed in an HTML file by using the following tag.

<object id="testObject" type="image/svg+xml" data="img/test.svg"></object>

Is there some way for me to get fill value of fill1,fill2 and fill3 using javascript or jquery. Also would it be possible to change these fill colors?

1 Answer 1

1

With generic Javascript, you can obtain the CSSStyleSheet object and manipulate any individual CSSStyleDeclaration:

// obtain document of object
var objectDoc = document.getElementById('testObject').contentDocument;
// obtain stylesheet
var stylesheet = objectDoc.getElementById('style1').sheet;

// find a certain rule
var rule2 = Array.from(stylesheet.cssRules).find(function (rule) {
    // make sure you reference a style rule and identify by selector string
    return rule.type === CSSRule.STYLE_RULE && rule.selectorText === '.fill2';
});

// get fill value
rule2.style.getPropertyValue('fill');
// set a different fill
rule2.style.setProperty('fill', '#676869');
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, but I get error "Uncaught TypeError: rule2.setProperty is not a function" when trying this
oops, sorry, there was a CSSStyleRule.style missing. See edit.
Works perfectly. Thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.