user14718152
user14718152

Reputation:

How to add array to includes() javascript

Im using composedPath for detect click outer of elements, but if elements more then 1 i need to add them all in if(). Maybe in js have another way? Im trying .includes(document.querySelectorAll(".js-open-user")); But thats not work.

document.addEventListener("click", (event) => {
let b1 = event
        .composedPath()
        .includes(document.querySelectorAll(".js-open-user")[0]);

let b2 = event
        .composedPath()
        .includes(document.querySelectorAll(".js-open-user")[1]);

let b3 = event
        .composedPath()
        .includes(document.querySelectorAll(".js-open-user")[2]);

if (!b1 && !b2 && !b3) this.closeUser();
});

Upvotes: 0

Views: 368

Answers (2)

axelduch
axelduch

Reputation: 10849

You can convert a NodeList to an array by using Array.prototype.slice.call(). Then using Array.prototype.some() to check that at least one matches the criterion, if not you can use this.closeUser() which is not implemented in my example.

document.addEventListener("click", (evt) => {
  const openUsers = Array.prototype.slice.call(document.querySelectorAll('.js-open-user'));
  const composedPath = evt.composedPath();
  
  if (!openUsers.some(user => composedPath.includes(user))) {
    // no open users found...
    alert('no matches!');
    return;
  }
  
  alert('match!');
});
<div class="js-open-user">hi</div>
<div class="js-open-user">oop</div>
<div class="js-open-user">test</div>
<div class="js-open-user">last one</div>

Upvotes: 1

szatkus
szatkus

Reputation: 1385

const nodes = document.querySelectorAll(".js-open-user");
const intersection = event.composedPath().filter(n => nodes.includes(n));

Upvotes: 0

Related Questions