Created
August 8, 2020 19:51
-
-
Save Xseba360/9b0be089a580eadbe9deb79296f7c7b7 to your computer and use it in GitHub Desktop.
turn all svgs in img tags into inline svg
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const li = document.querySelectorAll('img.svg'); | |
| li.forEach(function(element, index) { | |
| const imgID = element.getAttribute('id') | |
| const imgURL = element.getAttribute('src') | |
| const req = new XMLHttpRequest(); | |
| req.open('GET', imgURL, false); | |
| req.send(null); | |
| if(req.status == 200) { | |
| // Get the SVG tag, ignore the rest | |
| const svg = new DOMParser().parseFromString(req.responseText, "text/xml").querySelector('svg'); | |
| // Add replaced image's ID to the new SVG | |
| if (imgID !== null) { | |
| svg.id = imgID; | |
| } | |
| element.classList.add('replaced-svg') | |
| // Add replaced image's classes to the new SVG | |
| svg.setAttribute('class', element.getAttribute('class')) | |
| // Remove any invalid XML tags as per http://validator.w3.org | |
| svg.removeAttribute('xmlns:a') | |
| // Replace image with new SVG | |
| element.replaceWith(svg) | |
| } | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment