Peter Pan Peter Pan - 4 months ago 18
jQuery Question

Jquery && selector

I want to check if every single div inside my div(with id#row1) has the property "pointer-events" set to "none". And only if ALL OF THEM have that property do something.

How I did it is very bad but it works:

if( $('#row1 div:nth-child(1)').css("pointer-events") === "none"){

if( $('#row1 div:nth-child(2)').css("pointer-events") === "none"){Do something}}


Is there a simple way to check this? Something like this:

if(($('#row1 div:nth-child(1) && #row1 div:nth-child(2)')).css("pointer-events") === "none"){
Do something
}

Answer

jQuery doesn't seem to have a .all or .every method, but you can use Array.prototype.every (or [].every) for this:

var allHavePointerEventsNone = [].every.call($("#row1 div"), function(el) {
  return $(el).css("pointer-events") === "none";
});

Test:

// HTML
<div id="foo">
  <div class="yes"></div>
  <div class="yes"></div>
  <div class="yes"></div>
</div>

<div id="bar">
  <div class="yes"></div>
  <div class="yes"></div>
  <div class="no"></div>
</div>

// JS
console.log([].every.call($("#foo div"), function(el) {
  return $(el).hasClass("yes");
}));

console.log([].every.call($("#bar div"), function(el) {
  return $(el).hasClass("yes");
}));

Output:

true
false

https://jsfiddle.net/Dogbert/41wqf94p/

Comments