Now there is a need to select all elements with background images.
This problem is a bit tricky. We cannot use selection expressions to complete this problem.
Use jQuery's DOM filter method filter(), Elements can be selected based on any condition expressed in the function.
The filter method in jQuery allows passing a string (that is, a selector expression) as a parameter.
Or a function is passed. It The return value of will define whether an element is selected.
The function passed will be run on each element in the current selection set.
When the function returns false, the corresponding function is deleted from the selection set. Each time When the return value is true, the corresponding element
is not affected.
jQuery('*').filter(function(){
return !!jQuery(this).css('background');
});
The above code selects all elements with a background image.
The initial collection is all elements (*). Then filter() is called with a function as a parameter.
This function is performed on each collection whether it has the attribute background Judgment of attributes,
If it exists, keep it. Otherwise, delete this element from the result set.
What you see!! It is any undefined, empty type, and of course false in the middle of javascript.
If the function call returns these values, then the function returns false, thereby removing the
element without a background attribute from the collection.
Actually, !! is not necessary. Because jQuery will Convert these return values to Boolean types. But it's still a good idea to keep them.
That way anyone looking at your code can be absolutely sure of your intent. (This helps with code readability. ).
In the function passing filter(), you can refer to the current element through the this keyword.
Include it in the jQuery function and it becomes a jQuery object.
this //Regular element object.
jQuery(this) //jQuery object.
Here are some examples to stimulate your imagination.
jQuery('div').filter(function(){
var width = jQuery(this).width;
return width >100 && widht < 200;
});
//Return elements with 10 or 20 child elements.
jQuery('*').filter(function(){
var children = jQuery(this).childern().length;
return children ===10 || children ===20;
});
The following is a code example: determine the elements with a background color and change all their background colors to black.
Bye Bye Beautiful
Nothing but the girl
The Lazy song
If I die young
New soul