Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you access the contents of an SVG file in an <img> element?

Say you have this in your HTML:

<img src='example.svg' />

How would you access the contents ( ie. <rect>, <circle>, <ellipse>, etc.. ) of the example.svg via JavaScript?

like image 877
user783146 Avatar asked Nov 12 '11 04:11

user783146


People also ask

Can I use SVG in IMG?

From IE9 and above you can use SVG in a ordinary IMG tag..

How do I view an SVG image?

SVG images can be written directly into the HTML document using the <svg> </svg> tag. To do this, open the SVG image in VS code or your preferred IDE, copy the code, and paste it inside the <body> element in your HTML document.

Can SVG images be searched in HTML?

SVG is, essentially, to graphics what HTML is to text. SVG images and their related behaviors are defined in XML text files, which means they can be searched, indexed, scripted, and compressed. Additionally, this means they can be created and edited with any text editor or with drawing software.


1 Answers

It's not possible to get the DOM of a referenced svg from the img element.

If you use <object>, <embed> or <iframe> however then you can use .contentDocument (preferred) to get the referenced svg, or .getSVGDocument which may be more compatible with old svg plugins.

Here's an example showing how to get the DOM of a referenced svg.

like image 112
Erik Dahlström Avatar answered Sep 19 '22 15:09

Erik Dahlström