Dissecting jQuery – Filters
Advertisement
Advertisement
Advertisement
Advertisement
Advertisement
Read Time:
2 min
Sporadically, over the course of each month, we’ll post a “Dissecting jQuery” video quick tip. The idea behind these is that we’ll take a single chunk of the jQuery source at a time, break it down, and determine exactly what’s going on under the hood, so to speak. Then, with that knowledge, we’ll learn how to better utilize the library in our coding. Today, we’ll review filters.
Also available in this series:
- Dissecting jQuery – Filters
- Dissecting jQuery – The Text Method
jQuery’s Source for the :hidden
Filter
1 |
|
2 |
jQuery.expr.filters.hidden = function( elem ) { |
3 |
var width = elem.offsetWidth, height = elem.offsetHeight, |
4 |
skip = elem.nodeName.toLowerCase() === "tr"; |
5 |
|
6 |
return width === 0 && height === 0 && !skip ? |
7 |
true : |
8 |
width > 0 && height > 0 && !skip ? |
9 |
false : |
10 |
jQuery.curCSS(elem, "display") === "none"; |
11 |
};
|
The :visible
Filter
Quite cleverly, the :visible
filter only needs to call the hidden
method, and return the reciprocal.
1 |
|
2 |
jQuery.expr.filters.visible = function( elem ) { |
3 |
return !jQuery.expr.filters.hidden( elem ); |
4 |
};
|
Full Screencast

);"> jQuery source code to view a listing of other helpful filters that are available to you.
Harnessing this Knowledge to Extend jQuery
1 |
|
2 |
<script> |
3 |
$('p:first').data('info', 'value'); // populates $'s data object to have something to work with |
4 |
|
5 |
$.extend( |
6 |
jQuery.expr[":"], { |
7 |
block: function(elem) { |
8 |
return $(elem).css("display") === "block"; |
9 |
},
|
10 |
|
11 |
hasData : function(elem) { |
12 |
return !$.isEmptyObject( $(elem).data() ); |
13 |
}
|
14 |
}
|
15 |
);
|
16 |
|
17 |
$("p:hasData").text("has data"); // grabs paras that have data attached |
18 |
$("p:block").text("are block level"); // grabs only paragraphs that have a display of "block" |
19 |
</script> |
Note:
jQuery.expr[':']
is simply an alias forjQuery.expr.filters
.
Stay tuned. In future episodes, we’ll continue to slice out more chunks of the jQuery source, and dissect them!
Advertisement
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Sign upHi, I'm Jeffrey. I'm the creator of Laracasts and spend most of my days building the site and thinking of new ways to teach confusing concepts.
Advertisement
Advertisement
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.