← Back to jQuery Course | Chapter 7: DOM Traversing | Lesson 6 of 10

Filtering Nodes

filter() keeps elements that match a condition.

filter()

.filter() narrows an existing jQuery selection down to only the elements that satisfy a selector or test function you supply. Unlike find(), it never looks at descendants -- it only keeps or drops elements already in the current selection.

Example: filter()

javascript
<!DOCTYPE html>
<html>
  <head>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  </head>
  <body>
    <li>One</li><li class="done">Two</li><li class="done">Three</li>
    <script>
      console.log($("li").filter(".done").length);
    </script>
  </body>
</html>

not()

not() removes elements that match a selector from the current selection, effectively the opposite of filter(). It's useful when it's easier to describe which elements to exclude than which ones to keep.

Example: not()

javascript
<!DOCTYPE html>
<html>
  <head>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  </head>
  <body>
    <li>One</li><li class="done">Two</li>
    <script>
      console.log($("li").not(".done").length);
    </script>
  </body>
</html>

eq()

eq() selects the element at a specific zero-based index within the current selection, similar to indexing into an array. Passing a negative index counts from the end of the selection instead of the start.

Example: eq()

javascript
<!DOCTYPE html>
<html>
  <head>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  </head>
  <body>
    <li>One</li><li>Two</li><li>Three</li>
    <script>
      console.log($("li").eq(1).text());
    </script>
  </body>
</html>

first() and last()

first() and last() make the two most common filtering tasks -- grabbing just the first or last matched element -- quick to write without needing eq(0) or a length calculation. Both are shorthand for the equivalent eq() call.

Example: first() and last()

javascript
<!DOCTYPE html>
<html>
  <head>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  </head>
  <body>
    <li>One</li><li>Two</li><li>Three</li>
    <script>
      console.log($("li").first().text(), $("li").last().text());
    </script>
  </body>
</html>

Filtering Practice

Filtering helps you work with only the elements you actually need out of a broader selection, such as narrowing all list items down to just the ones marked as completed. It keeps later code simpler by acting on an already-precise set.

Example: Filtering Practice

javascript
<!DOCTYPE html>
<html>
  <head>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  </head>
  <body>
    <li class="done">Task 1</li><li>Task 2</li>
    <script>
      console.log($("li").filter(".done").length + " completed");
    </script>
  </body>
</html>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.