How to Select Element That Does Not have Specific Class

JavascriptHtmlClass

Javascript Problem Overview


I'm wondering how to select an element that does not have a specific class using JavaScript, not jQuery.

For example, I have this list:

<ul id="tasks">
  <li class="completed selected">One Task</li>
  <li>Two Task</li>
</ul>

and I select the completed task by:

var completeTask = document.querySelector("li.completed.selected");

But then I'm not sure how to select the list item that does not have those classes.

Javascript Solutions


Solution 1 - Javascript

This selects the second LI element.

document.querySelector("li:not([class])")

or

document.querySelector("li:not(.completed):not(.selected)")

Example:

// select li which doesn't have a 'class' attribute...
console.log(document.querySelector("li:not([class])"))

// select li which doesn't have a '.completed' and a '.selected' class...
console.log(document.querySelector("li:not(.completed):not(.selected)"))

 <ul id="tasks">
    <li class="completed selected">One Task</li>
    <li>Two Task</li>
  </ul>

Solution 2 - Javascript

To select the <li> that has not completed nor selected class:

document.querySelector("li:not(.completed):not(.selected)");

Fiddle

http://jsfiddle.net/Z8djF/

Solution 3 - Javascript

You can try the :not() selector

var completeTask = document.querySelector("li:not(.completed):not(.selected)");

http://jsfiddle.net/UM3j5/

Solution 4 - Javascript

document.querySelectorAll('[wf-body=details] input:not(.switch):not(.btn)').forEach(function(e){
    // do whatever you want. with 'e' as element :P
});

Solution 5 - Javascript

The :not(*selector*) selector also accepts commas (so does querySelectorAll()):

let plainElements = document.querySelectorAll( ':not( .completed, .in-progress ) ');
plainElements.forEach( ( item ) => { item.style.color = 'red'; } );

li { color: green; }

<ul id="tasks">
  <li class="completed selected">Task 1</li>
  <li>Task 2</li>
  <li class="in-progress">Task 3</li>
</ul>

Solution 6 - Javascript

Try getting an array of the parent's children instead:

var completeTask = document.querySelector("#tasks").childNodes;

Then loop/search them as necessary.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJaeeun LeeView Question on Stackoverflow
Solution 1 - JavascriptNick GrealyView Answer on Stackoverflow
Solution 2 - JavascriptBeNdErRView Answer on Stackoverflow
Solution 3 - JavascriptMusaView Answer on Stackoverflow
Solution 4 - JavascriptBurhan IbrahimiView Answer on Stackoverflow
Solution 5 - JavascriptIgor BeuermannView Answer on Stackoverflow
Solution 6 - JavascriptcrunchView Answer on Stackoverflow