Skip to content
Advertisement

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();
});

Advertisement

Answer

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>
Advertisement