0

So, I was going through this article about the danger when using Stopping Event Propagation. There in the section where it is described what else to do instead of using stopPropagation, this code is shown:

$(document).on('click', function(event) {
  if (!$(event.target).closest('#menucontainer').length) {
    // Hide the menus.
  }
});

What I didn't get here is why the length property is used in the statement? Isn't the closest enough to determine whether the clicked element is the event target?

Benjamin Smith Max
  • 2,668
  • 8
  • 33
  • 56
  • See [Is there an “exists” function for jQuery?](http://stackoverflow.com/q/31044/1048572) – Bergi Sep 29 '15 at 12:05

2 Answers2

1

Because .closest() always returns a jQuery object which is truthy, so of if just check for the value returned by .closest it will never satisfies the condition.

Instead the length property of the jQuery object will return the number of dom elements referred by it, so to check whether the closest found the targeted element in the ancestor tree of the e.target we can check the length property. If no matching element is found length will be 0 else it will have the number of references found

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

This a very often used 'hack' (I could say idiom instead, so widespread). Instead of checking the size of an array is greater than zero, you can shorten the code, by relying on the truthy-falsy properties of JavaScript objects.

if (array.length > 0) {
    // do something
}

is really the same as

if (array.length) {
    // do something
}

This predicate is true, when array is not falsy, it has the length property set, and its value is not falsy (false, 0, NaN, null and undefined is falsy).

In this case we are not using array, but an NodeList, but it has a length, so the principle is the same.

meskobalazs
  • 15,741
  • 2
  • 40
  • 63