4

I need to compare two hex values that are coming from a xml tag attribute field, I'm trying this:

var fill = $(this).attr( "fill" );
// console.log( fill.toString(16) );
if ( fill === "#FF00FF" )

But is not working any ideas?

Ricardo Sanchez
  • 4,935
  • 11
  • 56
  • 86

3 Answers3

1

I think you have to use 2 equal signs there, try this...

var fill = $(this).attr( "fill" );
if ( fill == "#FF00FF" )

If that doesn't work, then you probably not identifying $(this)

Nickolas Tuttle
  • 208
  • 2
  • 10
  • *"I think you have to use 2 equal signs there"* No. `attr` returns a string, so we don't need type coercion (it's almost always better not to rely on type coercion anyway, the rules are a bit complex). – T.J. Crowder May 12 '12 at 08:00
  • Working now, I wonder by the === fails if both are of string type? – Ricardo Sanchez May 12 '12 at 08:00
  • @RicardoSanchez: It ought not to. What happens if you `console.log(typeof fill)`? – T.J. Crowder May 12 '12 at 08:01
  • I have run into that a lot, and now i just rely on the == instead of === if the values can look the same, but not necessarily both be the same type of variable. – Nickolas Tuttle May 12 '12 at 08:05
1

attr returns a string, there's no need to call toString on it (and the argument will be ignored, because String's toString doesn't take an argument).

Your code is assuming a couple of things:

  1. That the attribute comes back in #hex form (if it's a color value, this is not reliably true cross-browser).

  2. That it will be in all upper case.

Not knowing what you see when you log the value, I'll just address the second part:

var fill = $(this).attr( "fill" );
if ( fill.toUpperCase() === "#FF00FF" )
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

If fill is a color, then it might be returned in RGB-format. And when you log it you write toString(). Either compare it with a RGB-value or compare it with a string as fill.toString(16)

superM
  • 8,605
  • 8
  • 42
  • 51