nicolas
nicolas

Reputation: 21

Get fill color of svg rectangle with plain javascript

I have a pretty simple question, but i'm really stuck on this and can't get it working.

I have an svg that contains a rectangle with an id 'bridge'. I want to get its fill color in console.

I thought "document.getElementById('bridge').style.fill" should work but it just returns an empty string. I tried some other ways but they all didn't work.

Please help me to get rectangle's fill color with plain javascript and explain why style.fill return an empty string.

let bridge=document.getElementById('bridge');

bridge.addEventListener('click', function() { console.log(bridge.style.fill); });
<svg id="game" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 600 300">
  <rect id="bridge" x="200" y="100" width="200" height="300" rx="10" fill='#80c41e'/>
</svg>

Upvotes: 0

Views: 1139

Answers (2)

Robert Longson
Robert Longson

Reputation: 124049

You want the computed style because you've set a mapped CSS property via an attribute so the style setting is indirect.

let bridge=document.getElementById('bridge');

bridge.addEventListener('click', function() {
console.log(window.getComputedStyle(bridge).getPropertyValue('fill')); });
<svg id="game" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 600 300">
  <rect id="bridge" x="200" y="100" width="200" height="300" rx="10" fill='#80c41e'/>
</svg>

Alternatively you could actually use a style rather than a mapped attribute i.e.

let bridge=document.getElementById('bridge');

bridge.addEventListener('click', function() {
console.log(bridge.style.fill);
bridge.style.fill='red'});
<svg id="game" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 600 300">
  <rect id="bridge" x="200" y="100" width="200" height="300" rx="10" style="fill:#80c41e;"/>
</svg>

As that makes it easier to set a new style.

Upvotes: 0

sbgib
sbgib

Reputation: 5828

Try using getAttribute() instead:

let bridge = document.getElementById('bridge');

bridge.addEventListener('click', function() {
  console.log(bridge.getAttribute('fill'));
});
<svg id="game" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 600 300">
  <rect id="bridge" x="200" y="100" width="200" height="300" rx="10" fill="#80c41e"/>
</svg>

Upvotes: 1

Related Questions