Skip to content
Advertisement

querySelectorAll returns me all elements that include the :not(class)

Note: I will only accept pure js answers, not jquery or any other js library.

I have a onchange method attached to a selector

const filter = (element) => {
    const value = document.getElementById(element).value;

    elements = document.querySelectorAll("table:not("+value+")");

    console.log(value, elements, "table:not("+value+")");
}

We get the element’s value which in this case could be of two options: is-room-type-false and is-room-type-true. These classes are attached to every single table on the page (there could be hundreds) When I run this and get the console.log

I see:

is-room-type-true // Selected value
8200 tables, node list. // The list of elements that supposedly do not contain this class.

Inspecting the giant array is showing me:

0: table.is-room-type-false.venue-id-1
1: table // Child should not be here
2: table .... (repeats for children tables) // none of these should be here.
x (some number later): table.is-room-type-true.venue-id-1 // Should not be here  ...

I wonder if its because of the second class attached to tables(?)

The tables can have nested tables, so I need just the parent tables (if possible) to come back, not their children.

Also as you can see from the sample output, my value is is-room-type-true but as we can see not only do I get children back, but also tables with the class in question when I specifically stated: tables WITH OUT this class.

So the question is:

  1. Whats wrong with my JS function to return me every single table including ones with the class applied.
  2. How do query such that my node list only shows parent tables? (if possible)

The idea is to then take these tables that do not have said class that was selected and then hide them:

    [].forEach.call(document.querySelectorAll("table:not("+value+")"), function (el) {
        el.style.visibility = 'hidden';
    });

But if I add this code to the above function, ALL TABLES hide (which is wrong)

Thoughts?

Advertisement

Answer

"table:not("+value+")" needs to be "table:not(."+value+")" so that it treats value as a class name.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement