1. .filter(selector)
This usage is based on the given selector parameter (jquery selectorexpression in the matched element) to filter, and then package the matching elements into a jquery element collection and return it. This method is used to narrow the matching scope. The selector parameter can be multiple expressions connected with commas.Look at the example:
HTML code:
Jquery code:
$("ul>li").filter(":even").css("color","red"); //将索引为偶数的li背景变为红色
The above jquery code has the same effect as the following jquery code
$("ul>li:even").css("color","red"); //将索引为偶数的li背景变为红色
Let’s take a look at the usage of connecting selector expressions with commas:
$("ul>li").filter(":even,.item").css("color","blue"); //将索引为偶数和calss为item的li背景变为蓝色
The demo example is as follows:
2. .filter( function(index) )
This method of use is to traverse the matching elements. If the value returned by function(index) is true, then this element will be selected. If the return value is false, then this element will be selected. The element will not be selected
The index parameter is the index of the current matching element in the original element collection.Example below:
HTML code:
jquery code:
$("p").filter(function(index) { return index == 1 || $(this).attr("id") == "fourth"; }).css("border", "5px double blue");
The result of the above code is the second p element with the id " The border of the p element of "fourth" has changed to a double line color and is blue
The demo example is as follows:
3. .filter(element)
# The ##element parameter is the Look at the example: Still looking at the above HTML code, look at the jquery code:$("p").filter(document.getElementById("third")).css("border", "5px double blue");
$("#third").css("border", "5px double blue");
4. .filter(jQueryobject)
This usage is the same as the above. The usage of filter(element) is similar, except that one parameter is a DOM object and the other parameter is a jquery object. Look at the example: Similarly to the above HTML code, look at the jquery code:$("p").filter($("#third")).css("border", "5px double blue");
It would be better to use the following jquery code directly:
$("#third").css("border", "5px double blue");
The above is the detailed content of Detailed explanation of the usage of filter() method to traverse DOM nodes. For more information, please follow other related articles on the PHP Chinese website!