1

I'm able to change fill attribute of an SVG rectangle with jQuery when I click on it.

But how can I get the actual fill attribute of this rectangle?

Here is my try:

$(document).ready(function () {
    var svg = $('#test_svg').find('#rect10')[0];
    $("#test_button").click(function(){
        console.log(svg.getAttribute('style'));
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test_svg" class="MusiopolisImages scaling-svg-container">
    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <svg
        id="svg8"
        version="1.1"
       
        class="scaling-svg" 
        viewBox="0 0 300 320" 
        height="200" 
        width="200">
        <g
            id="layer1"
            inkscape:groupmode="layer"
            inkscape:label="Calque 1">
            <rect
                y="100.54166"
                x="26.458334"
                height="69.547623"
                width="77.863091"
                id="rect10"
                style="fill:#ffffff;stroke-width:2;fill-opacity:1;stroke:#000000;stroke-opacity:1;stroke-miterlimit:4;stroke-dasharray:none"
            />
        </g>
    </svg>
</div>
<button id="test_button">Show rect10 fill attribute</button>

Edit: With this try I get the whole actual style of element #rect10 ("fill:#ffffff;stroke-width:2;fill-opacity:1;stroke:#000000;stroke-opacity:1;stroke-miterlimit:4;stroke-dasharray:none").

I'm so close! How can I get the fill attribute only?

3limin4t0r
  • 19,353
  • 2
  • 31
  • 52
  • Your svg has the id of `svg8` but you're selecting `#test_svg`. Where is the `#test_svg` element? – Sam R. Sep 20 '20 at 06:22
  • #test_svg is the id of the
    surrounding the svg. By replacing .find(#rect10) by .find('svg') I'm able to get any attribute of the svg. But I want to get the attribute fill of #rect10 which is inside the svg. How can I? Thanks for your help.
    – Etienne Guay Sep 20 '20 at 18:18
  • See @David's answer below. All you need is `let rect = document.querySelector('#rect10'); console.log(rect.style.fill);` – Sam R. Sep 20 '20 at 18:56
  • Thank you, exactly what I needed! – Etienne Guay Sep 20 '20 at 20:47

1 Answers1

2

You need to use the style attribute of the DOM Element:

example: alert(svg.style.fill)

David Rissato Cruz
  • 3,347
  • 2
  • 17
  • 17