jQuery Filtering

Apart from using css selectors to filter a elemnt we want, We can also use some built-in jquery methods to filter the element.

Method

Description

Example

first()

Selects the first element in the set of matched elements.

$("#container p").first().addClass("highlight");

last()

Selects the last element in the set of matched elements.

$("#container p").last().css("color", "blue");

q(index)

Selects the element at the specified index (0-based) in the set of matched elements.

$("#container p").eq(1).css("font-style", "italic");

filter(selector)

Reduces the set of matched elements to those that match the selector or pass the function's test.

$("#container p").filter(":contains('Third')").css("text-decoration", "underline");

not(selector)

Removes elements from the set of matched elements that match the selector.

$("#container p").not(":even").css("border", "2px dashed red");


Example
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>jQuery Filtering Example</title>
  <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
  <style>
    div {
      padding: 10px;
      margin: 5px;
      border: 1px solid #ccc;
    }
    .highlight {
      background-color: lightyellow;
    }
  </style>
</head>
<body>

<div id="parentContainer">
  <p>First paragraph.</p>
  <p>Second paragraph.</p>
  <p>Third paragraph.</p>
</div>

<script>
  // Using first() to select the first element and apply styling
  $("#parentContainer p").first().addClass("highlight");

  // Using last() to select the last element and apply styling
  $("#parentContainer p").last().css("color", "blue");

  // Using eq() to select a specific index (1-based) and apply styling
  $("#parentContainer p").eq(1).css("font-style", "italic");

  // Using filter() to select elements based on a condition and apply styling
  $("#parentContainer p").filter(":contains('Third')").css("text-decoration", "underline");

  // Using not() to select elements that do not match a condition and apply styling
  $("#parentContainer p").not(":even").css("border", "2px dashed red");
</script>

</body>
</html>

Quick Recap - Topics Covered

jQuery Filtering

Practice With Examples in Compilers

The Concepts and codes you leart practice in Compilers till you are confident of doing on your own. A Various methods of examples, concepts, codes availble in our websites. Don't know where to start Down some code examples are given for this page topic use the code and compiler.


Example 1
Example 1 Example 2 Example 3 Example 4 Example 5


Quiz


FEEDBACK