2

My index.html is

<object id="embed" data="test.html" width="500" height="500"
        type="text/xml"></object>
<script>
var test = document.getElementById("test");
var embed = document.getElementById("embed");
test.style.fill = "purple";
</script>

My test.html is

<style>
    #test {
        cx: 80%;
        fill: green;
    }
</style>
<svg width="500" height="500">
    <circle id="test" cx="50%" cy="50%" r="40%"
            stroke="black" stroke-width="1" fill="red" />
</svg>

I would like to apply css from the parent document to the loaded svg. I would also like to manipulate the svg using javascript in the parent document. The css works. JavaScript also works. They both modify position and fill, but they only work from the test.html document.

How do I manipulate and style embedded SVGs? I have a folder full of them and they can be mixed and relabeled, which is necessary for my larger project. I got a David Lynch plot sized headache reading up on the trainwreck of html imports and am avoiding them for now.

Prefer no jQuery.

zerodrama
  • 51
  • 1
  • 6
  • My understanding is that it works much the same as an iframe and can be accessed with contentDocument: `var svgObject = document.getElementById('embed').contentDocument;` but I am definitely no expert, so apologies in advance for any red herrings – lucas Aug 11 '18 at 23:58
  • Does the embed really have to be a HTML document containing the SVG? That's going to make things much more complicated. –  Aug 12 '18 at 00:46
  • Not necessarily. I can load them directly. So is contentDocument the same as innerHTML or is it an object with a DOM tree? – zerodrama Aug 12 '18 at 01:23
  • The onLoad trigger as explained by @jesús-otero [here] (https://stackoverflow.com/questions/32118167/how-can-i-get-the-text-inside-an-object-element) is necessary – zerodrama Aug 12 '18 at 02:15
  • It's a document object. From there you would do `var svg = svgObject.getElementById("test")` to get your circle – lucas Aug 12 '18 at 02:49
  • Is it possible to use css to target the svgObject hierarchy or do I need to add it to Shadow Root before that happens? – zerodrama Aug 12 '18 at 04:46

0 Answers0