Ali Shah lakhani
Ali Shah lakhani

Reputation: 105

How to change fill of svg which is linked using <object> tag in HTML?

I have an HTML file in which I have linked an svg object:

<object id="svgGlasses" type="image/svg+xml" data="images/glasses.svg"></object>

and glasses.svg as follows

<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
 width="42.604px" height="42.604px" viewBox="0 0 42.604 42.604" style="enable-background:new 0 0 42.604 42.604;"
 xml:space="preserve"> 
    <style type="text/css">
    <![CDATA[
        .circle{fill:#FAED24;}
    ]]>
    </style>
    <g id="Circle">
        <circle id="svgInternalID" class="circle" cx="21.302" cy="21.302" r="19.802"/>
    </g>
</svg>

When the user clicks on a button, which is in the HTML somewhere, I want the color of the circle to change to black.

I researched and found this JS, which I also added to the HTML, but it didn't work

var Head= document.getElementById("svgGlasses").contentDocument();
Head = Head.getElementById("svgInternalID");
Head.style.setProperty("fill","color", "#ff0000");

Is there any way to do it without using inline svg

Upvotes: 2

Views: 1314

Answers (1)

Robert Longson
Robert Longson

Reputation: 124249

Yes you can do it without inline SVG and you're pretty close to the right answer already.

You've the arguments in the wrong place for setProperty. This works for me:

var Head= document.getElementById("svgGlasses").contentDocument();
Head = Head.getElementById("svgInternalID");
Head.style.setProperty("fill","#000000", "");

The colour you want to set should be the second argument.

Upvotes: 4

Related Questions