5

I'd like to fill an svg file inside inside an <object> tag using javascript.

The problem is that .contentDocument returns null, therefore I can't fill the svg icon.

JSFiddle : http://jsfiddle.net/8kf36L0j/16/

I'm on the latest version of Firefox and Chrome, I read lots of other posts about this subject but I couldn't find something usefull to fix this issue.

HTML

<object id="svg_image_id" type="image/svg+xml" data="http://openclipart.org/people/StudioFibonacci/kitchen-blender.svg"></object>

Javascript

// Alternativ 1
alert(document.getElementById("svg_image_id").contentDocument); // .contentDocument == null ?
document.getElementById("svg_image_id").contentDocument.getElementById("path241").style.fill="red";

// Alternativ 2
var obj = document.querySelector("#svg_image_id");
var svg = obj.contentDocument.querySelector("svg"); // obj.contentDocument == null ?
svg.style.fill="red";
alert(svg);

Why is contentDocument returning null ? How can I fill the svg icon to another color ?

Horai Nuri
  • 5,358
  • 16
  • 75
  • 127

1 Answers1

-1

Make sure u are using the object element:

<object id="map" type="image/svg+xml">
  <img src="yourfallback.jpg" />
</object>

If obtaining a svg from a diffrent domain, use a fetch call

const map = document.querySelector('#map');
(async () => {
    const markup = await (await fetch('external-website.com/my.svg')).text();
    const blob = new Blob([markup], { type: 'image/svg+xml' });
    map.data = URL.createObjectURL(blob);

    map.onload = (e) => {
        const doc = map.getSVGDocument();
        doc.addEventListener('click', (e) => {
            console.log(e.target);
        });
    };
})();
Luhn
  • 706
  • 6
  • 15