Since 2015 there is an easy way to do this in plain JavaScript using the JavaScript Fetch API
"There was a time when XMLHttpRequest was used to make API requests.
Using jQuery, you could use the cleaner syntax of jQuery.ajax(). Now,
JavaScript has its own built-in way to make API requests." ~ Digital Ocean
- HTML: Give a class
svg
to the img
tags, which have a SVG file as a source.
<img class="svg" src="/images/logo-facebook.svg"/>
- JavaScript: Put this code in a separate file or inline, at the end of the
body
or in the head
, doesn't matter.
window.onload = () => {
// Find all <img> elements with a class of "svg"
const imgSVGs = document.querySelectorAll("img.svg");
// Loop over each found element
imgSVGs.forEach((img) => {
// Fetch the SVG file
fetch(img.getAttribute("src"))
.then(response => response.text())
.then(svgContent => {
// Parse the XML data from the SVG file into a DOM object for easier evaluation
const parser = new DOMParser();
const svgXML = parser.parseFromString(svgContent, 'text/xml');
// Create a new <svg> element
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
// Copy attributes from <img> to <svg>: class, alt, id
// Remove the helper class "svg"
svg.setAttribute("class", img.getAttribute("class"));
svg.classList.remove("svg");
if (img.getAttribute("id"))
svg.setAttribute("id", img.getAttribute("id"));
if (img.getAttribute("alt"))
svg.setAttribute("alt", img.getAttribute("alt"));
// Copy data from SVG file to <svg>: viewBox attribute, SVG path
svg.setAttribute("viewBox", svgXML.getElementsByTagName("svg")[0].getAttribute("viewBox"));
const path = svgXML.getElementsByTagName("svg")[0].querySelector("path");
svg.appendChild(path);
// Replace <img> with <svg>
img.parentNode.replaceChild(svg, img);
})
.catch(error => { console.log("Error fetching SVG: ", error); });
});
};
This short script transforms all img
elements with a class of svg
into real svg
elements, which can then be styled with CSS, like so:
svg:hover {
fill: red;
}
It copies the attributes id
, alt
and class
over from the <img>
to the <svg>
(if they are present) and takes the <path>
element and the viewBox
attribute from the original SVG file.
✔️ Same behavior as the accepted jQuery code, but with only JavaScript, no frameworks.