0

I am doing the following:

if ($('#selectYears option[value="' + $(this).val() + '"]') != null || $('#selectYears option[value="' + $(this).val() + '"]') != [] ) {
      console.log("inside if")
      $('#selectYears option[value="' + $(this).val() + '"]').remove().appendTo($('#selectYears'))
    } else {
      console.log("inside else")
      $('#selectedYears option[value="' + $(this).val() + '"]').remove().appendTo($('#selectYears'))
    }
})

If i do $('#selectYears option[value="my value"]') in Chrome's console I get []. But I am printing out inside if (therefore my check is failing). I need to get into the else in this case. Where am I wrong?

isherwood
  • 58,414
  • 16
  • 114
  • 157
connor moore
  • 611
  • 1
  • 8
  • 18
  • 1
    a jQuery selector cannot possibly be null or an empty array as it always returns a jQuery object. If you're trying to check if the element exists, use `length`, otherwise please explain a little more about what you're trying to do. – Rory McCrossan Feb 20 '15 at 14:32

1 Answers1

4

A jQuery selector never returns null or an array, it returns a jQuery object. It looks like an array in the console because it has properties that make it "array-like", but it isn't actually an array and will not compare equal to []. For more about this, see

What makes a jQuery object show up as an array in Chrome's Developer Tools?

If you want to know if anything was matched, use .length:

if ($('#selectYears option[value="' + $(this).val() + '"]').length != 0) {
Community
  • 1
  • 1
Barmar
  • 741,623
  • 53
  • 500
  • 612