jQuery filter()

Introduction

Return all <p> elements with class name "intro":

View in separate window

<!DOCTYPE html>
<html>
<head>
<script 
 src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>//from w w w  . j  a  v a 2  s . co  m
<script>
$(document).ready(function(){
  $("p").filter(".intro").css("background-color", "yellow");
});
</script>
</head>
<body>

<h1>Welcome to My Homepage</h1>

<p>This is a test.</p>
<p class="intro">I am from java2s.com.</p>
<p class="intro">CSS HTML.</p>
<p>This is another test.</p>

</body>
</html>

The filter() method returns elements that match a certain criteria.

$(selector).filter(criteria,function(index))
Parameter
Optional
Description
criteria



Optional.



a selector expression,
a jQuery object or
one or more elements.
To specify multiple criteria, use comma.
function(index)



Optional.



a function to run for each element in the set.
If it returns true, the element is kept.
Otherwise, the element is removed.
index - index position of the element in the set



PreviousNext

Related