jquery .not or
- Published
- Reading time
- 1 min read
- Length
- 289 words
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#
$(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:
<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:
<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.