How to Select Elements Without Specific Class in Javascript?

In javascript you can use css :not pseudo selector to select elements without specific class.

You can also select elements without specific id and attributes with :not pseudo selector.

For example, let’s presume you have unordered list of task and your code adds class ‘completed’ once the task is completed.

Now if you want to select all li elements that don’t have class ‘completed’, you can write the following code.

const uncompleteTasks = document.querySelectorAll("li:not(.completed)");

If you need to select all li elements that don’t have more than one specific classes (in our example anime and toei), you can write the following code.

const animation = document.querySelectorAll(“li:not(.anime):not(.toei)”);

const animation = document.querySelectorAll("li:not(.anime):not(.toei)");

In our next exmaple, let’s  select another element without specific class.

In this example we have three paragraphs and we want to select paragraph (<p> element) without the class select and add background and font color to it.

document.querySelector("p:not(.select)").style.background = "#41e2ba";

document.querySelector("p:not(.select)").style.color = "white";

This will select the second paragraph and give it background and font color property assigned by us.