Search code examples
javascriptqueryselector

How to select all the input elements except for the ones within a specific element


I want to select all the inputs in a form except those within a specific element.
Consider the following sample HTML:

<form id="myForm">
    <input />
    <input />

    <div class="excluded">
        <input />
        <input />
    </div>
</form>

The following doesn't work:

const myForm = document.getElementById("myForm");
const inputs = myForm.querySelectors(":not(.excluded) input");

I worked around it by setting special class names for those ones by doing this:

const exInputs = document.querySelectorAll(".excluded input");
exInputs.forEach(input => input.classList.add("excluded"));

Now, somewhere else, I could do this:

const inputs = myForm.querySelectorAll("input:not(.excluded)");

But, there must be a more straightforward method of excluding nested elements, right?!


Solution

  • Ok, I figured it out! It's basically the same :not() exclusion, but with a slight modification. So, Instead of:

    const input = myForm.querySelectorAll("input:not(.excluded input)")
    

    And that's it, turns out!

    According to MDN, and I quote:

    The :not() CSS pseudo-class represents elements that do not match a list of selectors. Since it prevents specific items from being selected, it is known as the negation pseudo-class.

    So, basically, whatever that goes in :not() gets compared to the attached element itself. Now, if that element matches the selectors within :not() it's gets negated; in other words, excluded.