Edit

jQuery Filtering

The jQuery filter methods are used to select a specific element based on its position in a group of elements. The jQuery filter methods are first(), last(), eq(), filter() and not() etc.

jQuery first() Method

The first() method is used to get the first element of the group of elements.

Example of Code

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("cite").first().css("background-color", "grey");
});
</script>
<br/><cite>First</cite><br/>
<cite>Second</cite><br/>
<cite>Third</cite>

Output


First
Second
Third

jQuery last() Method

The last() method is used to get the last element of the group of elements.

Example of Code

<script>
$(document).ready(function(){
  $("cite").last().css("background-color", "grey");
});
</script>
<br/><cite>First</cite><br/>
<cite>Second</cite><br/>
<cite>Third</cite>

Output


First
Second
Third

jQuery eq() Method

The eq() method is used to get the an element with a specific index number of the selected elements. The index numbers start at 0, so the first element will have the index number 0 and not 1.

Example of Code

<script>
$(document).ready(function(){
  $("samp").eq(1).css("background-color", "grey");
});
</script>
<br/><samp>First (index 0).</samp><br/>
<samp>Second (index 1).</samp><br/>
<samp>Third (index 2).</samp><br/>
<samp>Fourth (index 3).</samp>

Output


First (index 0).
Second (index 1).
Third (index 2).
Fourth (index 3).

jQuery filter() Method

The jQuery filter() method can take the selector to filters the set of matched elements based on a specific criteria.

Example of Code

<script>
$(document).ready(function(){
  $("article").filter(".example-jQuery-filter").css("background-color", "grey");
});
</script>
<br/><article>First</article><br/>
<article class="example-jQuery-filter">Second</article><br/>
<article class="example-jQuery-filter">Third</article><br/>
<article>Fourth</article>

Output


First

Second

Third

Fourth

jQuery not() Method

The not() method is used to get all elements that do not match the specific criteria. This method is the opposite of filter() method.

Example of Code

<script>
$(document).ready(function(){
  $("abbr").not(".example-jQuery-filter-not").css("background-color", "grey");
});
</script>
<br/><abbr>First</abbr><br/>
<abbr class="example-jQuery-filter-not">Second</abbr><br/>
<abbr class="example-jQuery-filter-not">Third</abbr><br/>
<abbr>Fourth</abbr>

Output


First
Second
Third
Fourth

jQuery has() Method

The jQuery has() method filters the set of matched elements and returns only those elements that has the specified descendant element.

Example of Code

<script>
$(document).ready(function(){
  $("p").has("span").css("background-color", "grey");
});
</script>
<p><span>First.</span></p>
<p>Second.</p>
<p>Third.</p>

Output

First.

Second.

Third.