-2

I am implementing a simple website which has a toggle sidebar. I want to make the sidebar be hidden when I clicked somewhere on the page except the sidebar. So I think that I should get all elements on the page except a element that has sidebar class. Is there any way to do like that with plain javascript? JQuery has :not() select for this, but I'm trying to not using JQuery... :(

Junhee Park
  • 143
  • 1
  • 9
  • 1
    `document.querySelectorAll()` has `:not()` as well. – Barmar Mar 06 '18 at 08:33
  • You don't need to get all the elements. The duplicate question has answers that show how to do it more efficiently with plain JS. – Barmar Mar 06 '18 at 08:36
  • @Barmar Oh, Thanks very much. Because of my poor English, I didn't think that I should have tried to search like that. Thanks – Junhee Park Mar 06 '18 at 08:53

1 Answers1

0

JQuery has :not() select for this

It's actually CSS, although jQuery extends it to allow all selectors (CSS's :not only allows a simple selector within the :not). Yours is a simple selector, so you can use :not:

var list = document.querySelectorAll(":not(.sidebar)");

However:

I want to make the sidebar be hidden when I clicked somewhere on the page except the sidebar.

I wouldn't implement this by setting an event handler on every element. Instead, I'd set a handler on document and then check to see if the event passed through the sidebar on the way to the document, e.g:

document.addEventListener("click", function(e) {
    if (e.target.closest(".sidebar")) {
        return; // The click passed through the sidebar
    }
    // close the sidebar
});

That uses Element#closest, which is present on all modern browsers and can be polyfilled for obsolete ones.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875