loading...
Cover image for How to convert image tags with SVG files into inline SVG tags

How to convert image tags with SVG files into inline SVG tags

luisaugusto profile image Luis Augusto Updated on ・1 min read

On many of the websites I have worked on that involve a CMS, the file manager does not handle SVGs very well. If I want to be able to store SVG icons or elements in the file manager, it is treated as an image and typically outputted using img tags, restricting any styling I'd like to add such as fill and stroke colors or animations. So, I created a function in JavaScript that would be able to run through the page for me and convert those img tags to inline svg:

It's a pretty simple function that takes a query and a callback as arguments. All you need to do is call that function with a query for the images you want to convert, and it will loop through each of them, fetch the SVG and use DOMParser to pull the SVG data from the file. After that, it copies the id and class attributes from the image to the SVG variable and replaces the image with the SVG data.

You can see it in action here, you'll notice that the html just has an image tag but if you inspect the page, it has been replaced with inline SVG. Now you can do whatever you want with the graphic!

Feel free to edit this to your needs, it's possible to copy over more than just the id and class attributes, and it would probably be good to do a test and check elements to make sure they are img tags before fetching data.

Posted on by:

luisaugusto profile

Luis Augusto

@luisaugusto

Fullstack JavaScript Developer based in Sacramento. When I'm not coding, I'm outside hiking and adventuring.

Discussion

markdown guide