How to read and change elements inside the svg file included using image tag in html or xhtml?

2k Views Asked by At

I am including SVG file inside the xhtml or html file using the below tag:

<ImageTexture id='colors' containerField='diffuseTexture'   url='http://localhost:3000/system/colorways/images/000/000/015/original/ShirtWithSolidColor03.svg?1544447759'></ImageTexture>

or

<image src="http://localhost:3000/system/colorways/images/000/000/015/original/ShirtWithSolidColor03.svg?1544447759">

So the svg get rendered into the xhtml or html file properly on the view.
But I want to change the properties of the path tag style fill present inside svg file is their any way to read the svg file using jquery or javascript included inside xhtml or html.
I am using ruby on rails for development. Thanks in advance

2

There are 2 best solutions below

1
Sven Liivak On

Youll have to bring svg to inline, then modify it at will.

<img class="svgClass" src="https://dev.w3.org/SVG/tools/svgweb/samples/svg-files/android.svg"></img>

<script>
  document.addEventListener("click", function() {
    var el = document.querySelectorAll("img");
    var e = el[0]; //or iterate
    var xhr = new XMLHttpRequest();
    xhr.open("GET", e.getAttribute("src"));
    xhr.send();
    xhr.onreadystatechange = function() {
        if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) e.outerHTML = xhr.responseText;

//svg is inline, access/modify as usual
        var elements = document.querySelectorAll('*[fill]');
        for (var i = 0; i < elements.length; i++){
            if(elements[i].getAttribute('fill') != "#FFF"){
                elements[i].setAttribute('fill', "#F00");
                elements[i].setAttribute('stroke', "#F00");
            }
        }
    };
  });
</script>
1
gengns On

You don't need to include it, change it and include it back.

1) Load your SVG file and overwrite fill property and value.

2) Insert your SVG into your image.

<!DOCTYPE html>
<head>
  <meta charset="UTF-8">
</head>
<body>
  <img>
  <script>
    const xhr = new XMLHttpRequest()
    xhr.open('GET', '/image.svg')

    xhr.onload = () => {
      if (xhr.status != 200) return;

      const svg = xhr.response
        .replace(/fill.+;/g, 'fill:blue')

      document.querySelector('img').src =    
        `data:image/svg+xml;charset=utf-8,${svg}`
    }

    xhr.send()
  </script>
</body>
</html>

Hope this help :)