How do I select elements that do not have a specific class using querySelectorAll?
Answers:
To select elements that do not have a specific class using
querySelectorAll, you can use the:not()pseudo-class in your CSS selector. Here's how you can do it:Example
Let's say you want to select all
<div>elements that do not have the classmy-class. You would use the following code:const elementsWithoutClass = document.querySelectorAll('div:not(.my-class)');Breakdown:
div- This part selects all<div>elements.:not(.my-class)- This part filters the selection to exclude any<div>that has the classmy-class.
Example in Action
Here’s a simple example demonstrating this:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Query Selector Example</title> </head> <body> <div class="my-class">This is a div with my-class</div> <div>This div does not have the class</div> <div class="another-class">This div does not have the my-class</div> <script> const elementsWithoutClass = document.querySelectorAll('div:not(.my-class)'); console.log(elementsWithoutClass); // Logs NodeList of divs that do not have 'my-class' </script> </body> </html>In this example, the
elementsWithoutClassvariable will contain all<div>elements that do not have the classmy-class, which in this case would be the second and third<div>elements.