Skip to content
the poor coder

jquery .not or

Poor Man
Published
Reading time
1 min read
On this page

Understanding jQuery .not() method#

As a web developer, you might have come across a situation where you need to select all elements from a set of matched elements except those that match a specific selector. This is where jQuery .not() method comes in handy.

Syntax#

Text
$(selector).not(filter)
  • selector: The set of matched elements to be filtered.
  • filter: The selector, function or element to be removed from the matched set.

Example#

Let's say we have a list of fruits and we want to select all fruits except bananas:

Text
<ul id="fruits">
  <li>Apples</li>
  <li>Bananas</li>
  <li>Oranges</li>
  <li>Pineapples</li>
</ul>

<script>
  $(document).ready(function(){
    $('#fruits li').not(':contains("Bananas")').css('color', 'green');
  });
</script>

Here, we have used the .not() method to filter out bananas from the list of fruits and applied a green color to the rest of the fruits.

Using Multiple Selectors#

You can also use multiple selectors with jQuery .not() method:

Text
<ul id="fruits">
  <li class="red">Apples</li>
  <li class="yellow">Bananas</li>
  <li class="orange">Oranges</li>
  <li class="green">Pineapples</li>
</ul>

<script>
  $(document).ready(function(){
    $('#fruits li').not('.red, .green').css('color', 'orange');
  });
</script>

Here, we have used multiple selectors to filter out items with classes red and green from the list of fruits and applied an orange color to the rest of the fruits.

Conclusion#

The jQuery .not() method is a powerful tool for filtering out elements from a set of matched elements based on a specific selector. It can be used in a variety of situations and can help you save a lot of time and effort. Hopefully, this article has given you a good understanding of how to use the .not() method in your own projects.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC