Select Page

Here is a jQuery code snippet that will replace all your images with the SVG codes and retain all classes that images have, getting added to the SVG class attribute.

// Replace image tag with svg
const replaceWithSVG = () => {
  let imgSelector = '.replaceWithSVG';

  $(imgSelector).each(function(index, element) {
    const totalElements = $(imgSelector).length;
    let classes = $(element).attr('class');
    if( $(element).attr('src') || $(element).attr('data-src') ){
      let imgsrc = '';
      if( $(element).attr('src') ){
        imgsrc = $(element).attr('src');
      }
      if( $(element).attr('data-src') ){
        imgsrc = $(element).attr('data-src');
      }

      fetch( imgsrc )
      .then((response) => response.text())
      .then((svgCode) => {
        let tempElement = $(svgCode);
        tempElement.addClass( classes );
        $(element).after(tempElement);
        $(element).remove();
        if (index === totalElements - 1) {
          setTimeout(function(){
            executeAfterSVGsLoaded("replaceWithSVG", function () {
              setTimeout(function(){
                console.log( $(imgSelector).length + ' image/s replaced with SVG' );
                runAfterSvgLoad();
              }, 1000);
            });
          }, 1000);
        }
      })
      .catch((error) => {
        console.error("Error fetching SVG image:", error);
      });
    }else{
      console.log( $(imgSelector).length + ' image/s already replaced with SVG' );
    }
  });
  
  if($(imgSelector).length == 0){
    setTimeout(function(){
      console.log( $(imgSelector).length + ' image/s replaced with SVG' );
      runAfterSvgLoad();
    }, 1000);
  }
}


// Run animations after SVG load
const runAfterSvgLoad = () => {
  // Code to run after SVG load
}