LATEST #JQUERY NEWS

How to Use jQuery’s .not() Method


jQuery’s .not() method is a method that allows you to return elements that do not match a particular criteria. Normally in jQuery, we use selectors to deliberately choose elements and apply jQuery code to them. Using the .not() method, however, we can choose every element except a specific element or type of elements to apply code to.

So if you want to apply a certain CSS rule to every div element in your project except for any div with the id #header, you can do so by using the not selector like this:

$("div").not("#header").css("color", "#000");

The code above will change all of the text color for every div element except divs who have the id of #header to black. The syntax for using the .not() selector is pretty simple. First, you use the selector to single out the element or the type of element you want your jQuery to not apply to. The parentheses take a few different parameters. They’ll either take criteria to help you further narrow down your selection, or you can add a function. To check out an example of other criteria you can use as a parameter to help you zero in on your selection (besides classes and ids), take a look at the example below:

$("li").not(":even").css("background-color", "#eee");

In the example above, the selector targets the “li” elements, and then you use “:even” as your criteria to select all li elements that are odd (so basically every other list element) and change the background color. What the code above essentially does is add zebra striping to your list elements (this can also be a cool effect to add to table elements — to do so simply replace the “li” with “tr” in your code). The .not() method is a great way to achieve both zebra striping and many other cool effects within your projects.