Categories
JavaScript Answers

How to select an element that does not have specific class with JavaScript?

Spread the love

To select an element that does not have a specific class using JavaScript, you can use a combination of the querySelectorAll() method and the :not() CSS pseudo-class selector.

For example, we write:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Select Elements Without Specific Class</title>
</head>
<body>
    <div class="element">Element 1</div>
    <div class="element">Element 2</div>
    <div class="element other-class">Element 3</div>
    <div class="element">Element 4</div>

    <script>
        // Select all elements with the class 'element' that do not have the class 'other-class'
        var elementsWithoutClass = document.querySelectorAll('.element:not(.other-class)');
        
        // Loop through the selected elements
        elementsWithoutClass.forEach(function(element) {
            console.log(element.textContent); // Output the text content of the element
        });
    </script>
</body>
</html>

In this example, we have several <div> elements with the class 'element', and one of them also has the class 'other-class'.

We use the querySelectorAll() method with the '.element:not(.other-class)' selector to select all elements with the class 'element' that do not have the class 'other-class'.

Then we loop through the selected elements using the forEach() method and log their text content to the console.

This way, only elements with the class 'element' but not the class 'other-class' will be selected.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *