Skip to content

How to change attributes and style of an svg embedded with <object/> from JavaScript

johnoye742johnoye742 Posts: 1
edited August 29 in Frontend

So once ran into this issue I had a to change svg from JavaScript but I was having some issues I search through the internet but the issue didn't seem to fix. I later solved the problem and here's the code:
let ic = document.querySelector("svgitem") let a = ic.contentDocument a.querySelector("#svgitem").style.stroke = "white"

Let me explain the code above. The ic variable is the object containing the svg and then you use ic.contentDocument to access the contents why? Cause embedding a svg within an object would mean the same thing as an iframe and the only way to get it's content is through contentDocument (or contentWindow if you're working specifically with an iframe).
So with this you can modify attributes and all.
But there's a downside though, If you're running this on your browser on file:// i.e a local file, this might not work for some browsers like Chrome (v49.0) and Opera (v35.0) on both Windows and Mac.

Comments

  • dhtmldhtml Posts: 27

    That is a very good one there. I will test this out myself.

Sign In or Register to comment.