0

Suppose I want to check the fill-opacity of a SVG element. I'd do this

elem.attr('fill-opacity');

This can give me back 0 if the element has no fill-opacity attribute or if the fill-opacity has been set to 0.

How do I distinguish between those two cases?

praks5432
  • 7,246
  • 32
  • 91
  • 156
  • Are you sure it gives back 0 if the element has no fill-opacity attribute? [This answer](https://stackoverflow.com/questions/1318076/jquery-hasattr-checking-to-see-if-there-is-an-attribute-on-an-element) leads me to believe it would return either `undefined` or `false`. – Maximillian Laumeister Aug 28 '15 at 23:05

2 Answers2

2

Can't you simply use elem.hasAttribute?

Nick Ooms
  • 21
  • 1
1

If fill-opacity is not specified, attr() returns undefined.

alert("fill-opacity (DOM) ="+document.getElementById("test").getAttribute("fill-opacity"));
alert("fill-opacity (jQuery) ="+$("#test").attr("fill-opacity"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<svg>
  <rect id="test" width="10" height="10"/>
</svg>
Paul LeBeau
  • 97,474
  • 9
  • 154
  • 181