Skip to main content
The 2024 Developer Survey results are live! See the results
simplify a line in JavaScript with more modern function
Source Link
lchristmann
  • 342
  • 4
  • 14
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.replaceChildreplaceWith(svg, img);
            })
            .catch(error => { console.log("Error fetching SVG: ", error); });

    });
};
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); });

    });
};
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.replaceWith(svg);
            })
            .catch(error => { console.log("Error fetching SVG: ", error); });

    });
};
minor formatting, typo and wording improvements
Source Link
lchristmann
  • 342
  • 4
  • 14
  1. HTML: GiveUse <img> tags and give a class of "svg" to theall those img<img> tags, which have aan SVG file as a source.
  1. JavaScript: Put this code in a separate file or inline, at the end of the body<body> or in the head<head>, doesn't matter.

This short script transforms all img<img> elements with a class of svg into real svg<svg> elements, which can then be styled with CSS, like so:

  1. HTML: Give a class svg to the img tags, which have a SVG file as a source.
  1. JavaScript: Put this code in a separate file or inline, at the end of the body or in the head, doesn't matter.

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:

  1. HTML: Use <img> tags and give a class of "svg" to all those <img> tags, which have an SVG file as a source.
  1. JavaScript: Put this code in a separate file or inline, at the end of the <body> or in the <head>, doesn't matter.

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:

Source Link
lchristmann
  • 342
  • 4
  • 14

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

  1. 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"/>
  1. 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.