DEV Community

Cover image for How to convert image tags with SVG files into inline SVG tags
Luis Augusto
Luis Augusto

Posted on • Updated on

Converting Img Tag How to convert image tags with SVG files into inline SVG tags

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.

Top comments (3)

akkis profile image
Akis Laoutaris

Great! thank you for sharing your solution.

vinsjava profile image

I am getting cors issue while using fetch! could you please help me to get out of the error?

tylr profile image
Tyler Robinson

Same issue here :/