jQuery Filtering

The first(), last(), eq(), filter() and not() Methods


In jQuery, the simplest filtering methods first(), last(), and eq() are used to target elements based on their position within a set of matched elements.

Additional methods like filter() and not() help you refine your selection by including only elements that meet or exclude those that don’t meet specific conditions.



jQuery first() Method


The .first() method in jQuery is used to select the first element from a group of matched elements.


The following example selects the first <div> element:


Example
<script>
$(document).ready(function(){
$("div").first().css("background-color", "yellow");
});
</script>

Try it yourself

jQuery last() Method


The .last() method in jQuery is used to select the last element from a set of matched elements.


The following example selects the last <div> element:

Example
<script>
$(document).ready(function(){
$("div").last().css("background-color", "yellow");
});
</script>

Try it yourself

jQuery eq() method


The .eq() method in jQuery is used to select a specific element based on its index position in a set of matched elements.


The index numbers start at 0, so the first element will have the index number 0 and not 1. The following example selects the second <p> element (index number 1):

Example
<script>
$(document).ready(function(){
$("p").eq(1).css("background-color", "yellow");
});
</script>

Try it yourself

jQuery filter() Method


The .filter() method in jQuery is used to narrow down a set of matched elements by keeping only those that match a specified selector, function, or criteria.

The following example returns all <p> elements with class name "intro":

Example
<script>
$(document).ready(function(){
$("p").filter(".intro").css("background-color", "yellow");
});
</script>

Try it yourself

jQuery not() Method


The .not() method in jQuery is used to remove elements from a set of matched elements that match a specific selector or condition.


Tip: The not() method is the opposite of filter().


The following example returns all <p> elements that do not have class name "intro":

Example
<script>
$(document).ready(function(){
$("p").not(".intro").css("background-color", "yellow");
});
</script>

Try it yourself


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.