jQuery Traversal - not() Method
Example
Removes the paragraph with id "selected" from the set containing all paragraphs:
$("p").not("#selected")
Definition and Usage
not() Removes elements from the matched element set.
Syntax 1
.not(selector)
Parameter | Description |
---|---|
selector | A string value that contains a selector expression used to match elements. |
Syntax 2
.not(element)
Parameter | Description |
---|---|
element | One or more DOM elements that need to be removed from the matched set. |
Syntax 3
.not(function(index))
Parameter | Description |
---|---|
function(index) | A function used to check each element in the collection. this is the current DOM element. |
Details
If a jQuery object representing a collection of DOM elements is given, the .not() method will construct a new jQuery object from a subset of the matched elements. The applied selector will check each element; elements that do not match the selector will be included in the result.
Consider the following page with a simple list:
<ul> <li>list item 1</li> <li>list item 2</li> <li>list item 3</li> <li>list item 4</li> <li>list item 5</li> </ul>
We can apply this method to the set of list items:
$('li').not(':even').css('background-color', 'red');
The result of this call is to set the background color of items 2 and 4 to red, because they do not match the selector (remember, :even and :odd both use an index based on 0).
Remove specific elements
The second version of the .not() method allows us to remove elements from the matched set, assuming we have already found these elements through other means. For example, imagine a list that has already applied an id to one of the items:
<ul> <li>list item 1</li> <li>list item 2</li> <li id="notli">list item 3</li> <li>list item 4</li> <li>list item 5</li> </ul>
We can use the native JavaScript function getElementById() to read the third list item and then remove it from the jQuery object:
$('li').not(document.getElementById('notli')).css('background-color', 'red');
This statement changes the background color of items 1, 2, 3, and 5. We can achieve the same thing with a simpler jQuery expression, but this technique can be very useful when, for example, other libraries provide references to pure DOM nodes.
For jQuery 1.4, the .not() method can take a function as its parameter, just like the .filter() method. Elements for which the function returns true will be excluded from the filtered set; all other elements will be included.