SlideShare a Scribd company logo
1 of 61
Download to read offline
Beyond the Final
Frontier of jQuery
Selectors
Alexander Shopov
<ash@kambanaria.org>
[ash@edge ~]$ whoami
By day: Software Engineer at Cisco
By night: OSS contributor
Coordinator of Bulgarian Gnome TP
Contacts:
E-mail: ash@kambanaria.org
Jabber: al_shopov@jabber.minus273.org
LinkedIn: http://www.linkedin.com/in/alshopov
SlideShare: http://www.slideshare.net/al_shopov
Web: Just search “al_shopov”
Please Learn And Share

License: CC-BY v4.0
Contents
●

The Bold And the Beautiful

●

Guiding Light

●

As The World Turns
The Bold And the Beautiful
Bold!
<style>.bold {font-weight: bold}</style>
<div id="d" class="bold">This is bold</div>
<script>jQuery(function (){
console.log(jQuery('#d').css('font-weight'));
});
</script>
Bold!!
<style>.bold {font-weight: bold}</style>
<div id="d" class="bold">This is bold</div>
<script>jQuery(function (){
console.log(jQuery('#d').css('font-weight'));
});
</script>

Chrome/Safari/Opera
bold
Bold??
<style>.bold {font-weight: bold}</style>
<div id="d" class="bold">This is bold</div>
<script>jQuery(function (){
console.log(jQuery('#d').css('font-weight'));
});
</script>

Chrome/Safari/Opera
bold

IE11/Firefox
700
Thus Spoke The Standards
Value: normal | bold | bolder | lighter | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900
Initial: normal
Applies to: all elements
Inherited: yes
Percentage values: N/A
CSS1 [CSS Level 1/CSS Level 2 (Revision 1)/
CSS Transitions/CSS Fonts Module Level 3]
100
200
300
400
500
600
700
800
900

-

Thin
Extra Light (Ultra Light)
Light
Normal
Medium
Semi Bold (Demi Bold)
Bold
Extra Bold (Ultra Bold)
Black (Heavy)

100 ≤ 200 ≤ 300 ≤ 400 ≤ 500
≤ 600 ≤ 700 ≤ 800 ≤ 900
Beautiful

There is difference between
Italic and Oblique font shapes
● Do you know it?
●
Beautiful

Italics are stylized cursive writings –
as if we write by hand. They have
different shapes than roman/regular
● Obliques look like slanted
roman/regular – poor man's italics
●
The Three Graces – Roman/regular, Italic,
Oblique
How Can We Use Them With A Single Button?
How Can We Use Them? Web Fonts!
<style type="text/css">
@font-face {
font-family: lmr;
src: url(lmrtest-regular.otf);
}
@font-face {
font-family: lmr;
font-style: italic;
src: url(lmrtest-italic.otf);
}
@font-face {
font-family: lmr;
font-style: oblique;
src: url(lmrtest-oblique.otf);
}
</style>

<div style="font-family:lmr">
<p style="font-style:normal">
Roman
</p>
<p style="font-style:italic">
Italic
</p>
<p style="font-style:oblique">
Oblique
</p>
</div>
How Can We Find The Bold And The Beautiful?
function isBold(el){
var w = jQuery(el).css('font-weight');
return ('bold' === w) || (400 < (+w));
}

function isSlanted(el){
var s = jQuery(el).css('font-style');
return ('italic' === s) || ('oblique' === s) ;
}
Sorry Mario, Our Princess is in Another Castle
●
●

●

We did not find the elements
We can just check whether a particular element is what we are
interested in
So we use it like this and create functions time and again:

jQuery('selector …').filter(function(i){
return isBold(i);
});
A Slight Improvement
function bold4jQ(){
var w = jQuery(this).css('font-weight');
return ('bold' === w) || (400 < (+w));
}
jQuery('selector …').filter(bold4jQ);
function slanted4jQ(){
var s = jQuery(this).css('font-style');
return ('italic' === s) || ('oblique' === s);
}
jQuery('selector …').filter(slanted4jQ);
(You Gotta) Fight For Your Right (to jQuery)
●

●

●

Why do this imperatively and explicitly call time and agang the
same functions?
jQuery has its own selector engine, why not use it to
accomplish our needs
Let's be declarative – which is more readable?

jQuery('selector …').filter(bold4jQ);
jQuery('selector …').filter(slanted4jQ);
jQuery('selector:bold');
jQuery('selector:slanted');
Guiding Light
This Is How We Do It
jQuery.extend(jQuery.expr[':'], {
bold: function(el) {
var w = jQuery(el).css('font-weight');
return ('bold' === w) || (400 < (+w));
}
});
jQuery('div:bold');
jQuery.extend(jQuery.expr[':'], {
slanted: function(el) {
var s = jQuery(el).css('font-style');
return ('italic' === s) || ('oblique' === s);
}
});
jQuery('#editor span.usr:slanted');
Homework Asignments
●

Find external links

●

Find links that lead to ASPX or JSP pages directly

●

Find divs with sizes above 42px

●

Find spans that are block elements or divs that are inline

●

The sky is the limit
Is This All There Is?
●

We are not limited to no args functions. The function we provide
is called with 3 arguments. We can dispatch behaviour based
on all of them

/* returns boolean - whether given DOM
* element matches
matcher(
/* single DOMElement from currenlty
* matched set to check
DOMElement,
/* index of the current element in
* in the matched set
index,
/* array of the split matching
* sequence
matches);

*
*/
*
*/
*
*/
*
*/
Positional Parameters Example Usage
jQuery('selector…:font(14,400,italic)');
m = ['font', 'font', '', '14,400,italic'];
Positional Parameters Example Usage
jQuery('selector…:font(14,400,italic)');
m = ['font', 'font', '', '14,400,italic'];

m[3] === '14,400,italic';
Positional Parameters Example Usage
jQuery('selector…:font(14,400,italic)');
m = ['font', 'font', '', '14,400,italic'];

m[3] === '14,400,italic'; // split & coerce
m[3] === '14,400,italic';
Positional Parameters Example Usage
jQuery.extend(jQuery.expr[':'], {
font: function(el, i, m){
var a = m[3].split(','), // dispatch
l = a.length,
// dispatch
j = jQuery(el),
// cache
p = ['size', 'weight', 'style'],
z = 0;
// index
if(0 === l){return true;}
if(3
< l){throw {name:'Funky', message:'Nuts?'};}
// or return false and fail silently
for(;z<l;++z){if(j.css('font-'+p[z])!=a[z]){return false;}}
return true;
}});
Named Parameters Example Usage
jQuery('selector…:font' +
'(size>14,400<=weight,italic!=style,family!=Sans)'
m = ['font', 'font', '',
'size>14,400<=weight,italic!=style,family!=Sans'
Named Parameters Example Usage
jQuery('selector…:font' +
'(size>14,400<=weight,italic!=style,family!=Sans)'
m = ['font', 'font', '',
'size>14,400<=weight,italic!=style,family!=Sans'
m[3] === // what to do, what to do?
'size>14,400<=weight,italic!=style,family!=Sans'
Named Parameters Example Usage
'size>14,400<=weight,italic!=style,family!=Sans'
Named Parameters Example Usage
// split, split, juggle & check
'size>14,400<=weight,italic!=style,family!=Sans'
Named Parameters Example Usage
// split, split, juggle & check
'size>14,400<=weight,italic!=style,family!=Sans'
// split, juggle & check
['size>14','400<=weight','italic!=style','family!=Sans']
Named Parameters Example Usage
// split, split, juggle & check
'size>14,400<=weight,italic!=style,family!=Sans'
// split, juggle & check
['size>14','400<=weight','italic!=style','family!=Sans']
[['size','>','14'
],
['400','<=','weight' ],
['italic','!=','style'],
['family','!=','Sans' ]]

// juggle & check
Named Parameters Example Usage
// split, split, juggle & check
'size>14,400<=weight,italic!=style,family!=Sans'
// split, juggle & check
['size>14','400<=weight','italic!=style','family!=Sans']
[['size','>','14'
],
['400','<=','weight' ],
['italic','!=','style'],
['family','!=','Sans' ]]
[['family','!=','Sans'
['size' ,'>' ,'14'
['style' ,'!=','italic'
['weight','<=','400'

// juggle & check

],
],
],
]]

// check left as an
// excercise for the
// reader
Named Parameters Example Usage
Getting Jiggy With It
m[3] === // be creative
'size>14,400<=weight,italic!=style,family!=Sans'
'size>14,400<=weight,italic!=style,family!=Sans'
Named Parameters Example Usage
Getting Jiggy With It
m[3] === // be creative
'size>14,400<=weight,italic!=style,family!=Sans'
'size>14,400<=weight,italic!=style,family!=Sans'
'size>14,400<=weight,italic!=style,family!=Sans'.
replace(/,/g,'&&') === ???
Named Parameters Example Usage
Getting Jiggy With It
m[3] === // be creative
'size>14,400<=weight,italic!=style,family!=Sans'
'size>14,400<=weight,italic!=style,family!=Sans'
'size>14,400<=weight,italic!=style,family!=Sans'.
replace(/,/g,'&&') === ???
"size>14&&400<=weight&&italic!=style&&family!=Sans"
Looks familiar, doesnt' it?
var expression =
"size>14&&400<=weight&&italic!=style&&family!=Sans";

●

But what are size, weight, style, family?

●

What about italic and Sans?
But We Already Know That

size:
weight:
style:
family:

j.css('font-size')
j.css('font-weight')
j.css('font-style')
j.css('font-family')

italic: 'italic',
Sans:
'Sans'
Why Didn't You Say So?
var scope = {
size:
weight:
style:
family:

j.css('font-size'),
j.css('font-weight'),
j.css('font-style'),
j.css('font-family'),

italic: 'italic',
Sans:
'Sans'};
Mojo!!!

var r;
with (scope){
r = eval (expression);
}
// PROFIT!!!
Now That You Know How
●

DON'T!!!

●

Use to explore, you brave explorers.

●

Use in production is misuse – will void your warranty, kill kittens
and cause plague.
So What Is The Catch?
●

Quick to implement, experiment, POC;

●

Piggyback on JavaScript as a host for the DSL;

●

●

●

Hard to debug, with weird error messages in strange places – still
we are in control of the scope template and this can be mitigated;
Blocks browser's JS optimization engine (but we are not the only
ones);
Jslint will complain – we are treading in one of the the darkest
places in the language.
How Do You Say De-Groovie?
How Do You Say De-Bug?
jQuery('selector…:debug');
jQuery.extend(jQuery.expr[':'], {
debug: function(el, i, m) {
console.log("args: %o", arguments);
console.log("m: %o", m);
return true;
}
});
The Power Of Their Source? The Crystal!
https://github.com/jquery/jquery/blob/master/src/selector-sizzle.js
define(["./core", "sizzle"],
function( jQuery, Sizzle ) {
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.pseudos;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
});
As the World Turns
Sizzle, Who the (BLEEP) is Sizzle?
●

●

Sizzle: A pure-JavaScript CSS selector engine designed to be
easily dropped in to a host library.
Embedded in jQuery, MooTools, Dojo
Version Supported browsers

LOC

Minified API

jQuery 1.10.2

IE6+, FF(Current-1)+, Chrome(Current≈10k
1)+, Safari 5.1+, Opera 12.1x, (Current-1)+

≈93kB

Vast

jQuery 2.0.3

IE9+, FF(Current-1)+, Chrome(Current≈9k
1)+, Safari 5.1+, Opera 12.1x, (Current-1)+

≈84kB

Vast

Sizzle

IE6+, FF3.0+, Chrome 5+, Safari 3+,
Opera 9+

≈18kB

Tiny

1.10.1x

≈2k
Sizzle API – part 1

/* returns boolean - whether given DOM
* element matches selector
* If available uses native matchesSelector
Sizzle.matchesSelector(
/* DOMElement to check
DOMElement,
/* String – CSS Selector
selector);

*
*
*/
*/
*/
Sizzle API – part 2

/* returns Array of the elements that match
* the selector
Sizzle.matches(
/* String – CSS Selector
selector,
/* Array of DOMElements
elements);

*
*/
*/
*/
Sizzle API – part 3

/* Return nodes that match selector
* [starting from the context node]
* as an array [or added to the provided
*
array-like object]
Sizzle(
/* String – CSS Selector
selector,
/* Optional: DOMElement|DOMDocument
* Default: Current document
* Node to start the search from
context,
/* Optional: Array-like object to
*
add elements to
*
eg.: jQuery() obj
* Default: Create new array
results);

*/
*/
*
*
*/
*
*
*
*/
That's All Folks!

This was the
whole public API!
Do It Very Slowly (True Lies)
●

●

document.querySelectorAll is very fast and meddles with
our meddling
Get rid of it!

document.querySelectorAll = null; // or any falsy
// why not?
delete document.querySelectorAll;
Alien
●

querySelectorAll (as well as querySelector) comes from
elsewhere – from the prototype world

●

Prototype world is wilder that the West!

●

Object.getPrototypeOf() – IE, Chrome, Firefox

●

{}.__proto__ – Firefox, Chome
Alien 2 – IE 10
querySelectorAll

WORKS: = null;
FAILS: delete
Node
Protoype

document

Document
Protoype
Window
window

null
Object
Alien 4 – Firefox
querySelectorAll
WORKS: = null;
FAILS: delete

document

HTML
Document
Prototype

Document
Prototype

window

null

Node
Prototype

[Window
Prototype]

Event
Target
Prototype

Object
Alien 3 – Chrome
querySelectorAll

null

WORKS: = null;
FAILS: delete
Node

document

HTML
Document

Document

Window
window

Event
Target

Object
Alien 4 – Firefox
querySelectorAll
WORKS: = null;
FAILS: delete

document

HTML
Document
Prototype

Document
Prototype

window

null

Node
Prototype

[Window
Prototype]

Event
Target
Prototype

Object
What We Used Thus Far

// Thus far we actually extended
Sizzle.selectors.pseudos;
//jQuery does some magic to ease using
Sizzle.selectors.createPseudo(function(){});
Where Next
// Matches parts of selector (as string)
// divides in parts
Sizzle.selectors.match.NAME = new RegExp('...');
Sizzle.selectors.find.NAME = function(
// what was matched above
match,
// element to start search from
context,
// whether doc is XML/HTML
IsXML ) {};
// regex of orders, add |NAME to it
Sizzle.selectors.order;
Where Next
// quick prefilter, eg: remove all attributes or
// elements based on a quick decision
Sizzle.selectors.preFilter.NAME =
function( match ) {};
// slow filter invoked after the one above (if ∃)
// real evaluation
Sizzle.selectors.filter.NAME =
function(element, m1, m2, m3 ) {};
Sizzle is extensible
●

No extension tests in test harness;

●

Dragons around the corers, YMMV;

●

●

Looooooooooooooooo + ooooooooooooo + oooo + oooooo +
oooooooo + oooooo + ooooooooooooooooooooooooooo +
oooooooo + ooooooooooo + ooooong regular expressions;
Actual regular expressions are longer.
TO BE IMPROVED...

More Related Content

What's hot

Design Patterns the Ruby way - ConFoo 2015
Design Patterns the Ruby way - ConFoo 2015Design Patterns the Ruby way - ConFoo 2015
Design Patterns the Ruby way - ConFoo 2015Fred Heath
 
Learning the basics of the Drupal API
Learning the basics of the Drupal APILearning the basics of the Drupal API
Learning the basics of the Drupal APIAlexandru Badiu
 
Ruby and rails - Advanced Training (Cybage)
Ruby and rails - Advanced Training (Cybage)Ruby and rails - Advanced Training (Cybage)
Ruby and rails - Advanced Training (Cybage)Gautam Rege
 
ESWHO, ESWHAT, ESWOW -- FEDucation -- IBM Design
ESWHO, ESWHAT, ESWOW -- FEDucation -- IBM DesignESWHO, ESWHAT, ESWOW -- FEDucation -- IBM Design
ESWHO, ESWHAT, ESWOW -- FEDucation -- IBM DesignJosh Black
 
CGI::Prototype (NPW 2006)
CGI::Prototype (NPW 2006)CGI::Prototype (NPW 2006)
CGI::Prototype (NPW 2006)brian d foy
 
Theming Drupal 7 - Meet your new best friend, render()
Theming Drupal 7 - Meet your new best friend, render()Theming Drupal 7 - Meet your new best friend, render()
Theming Drupal 7 - Meet your new best friend, render()Erik Baldwin
 
Advanced Drupal Views: Theming your View
Advanced Drupal Views: Theming your ViewAdvanced Drupal Views: Theming your View
Advanced Drupal Views: Theming your ViewRyan Cross
 
WordPress 3.4 Theme Customizer
WordPress 3.4 Theme CustomizerWordPress 3.4 Theme Customizer
WordPress 3.4 Theme CustomizerChandra Maharzan
 
How to count money using PHP and not lose money
How to count money using PHP and not lose moneyHow to count money using PHP and not lose money
How to count money using PHP and not lose moneyPiotr Horzycki
 
Jquery optimization-tips
Jquery optimization-tipsJquery optimization-tips
Jquery optimization-tipsanubavam-techkt
 
Data::FormValidator Simplified
Data::FormValidator SimplifiedData::FormValidator Simplified
Data::FormValidator SimplifiedFred Moyer
 
jQuery Performance Rules
jQuery Performance RulesjQuery Performance Rules
jQuery Performance Rulesnagarajhubli
 
Beutiful javascript with coffeescript
Beutiful javascript with coffeescriptBeutiful javascript with coffeescript
Beutiful javascript with coffeescriptAmir Barylko
 

What's hot (20)

Form API 3
Form API 3Form API 3
Form API 3
 
Design Patterns the Ruby way - ConFoo 2015
Design Patterns the Ruby way - ConFoo 2015Design Patterns the Ruby way - ConFoo 2015
Design Patterns the Ruby way - ConFoo 2015
 
Learning the basics of the Drupal API
Learning the basics of the Drupal APILearning the basics of the Drupal API
Learning the basics of the Drupal API
 
SOLID Ruby, SOLID Rails
SOLID Ruby, SOLID RailsSOLID Ruby, SOLID Rails
SOLID Ruby, SOLID Rails
 
basics of css
basics of cssbasics of css
basics of css
 
DBI
DBIDBI
DBI
 
Jquery introduction
Jquery introductionJquery introduction
Jquery introduction
 
Ruby and rails - Advanced Training (Cybage)
Ruby and rails - Advanced Training (Cybage)Ruby and rails - Advanced Training (Cybage)
Ruby and rails - Advanced Training (Cybage)
 
ESWHO, ESWHAT, ESWOW -- FEDucation -- IBM Design
ESWHO, ESWHAT, ESWOW -- FEDucation -- IBM DesignESWHO, ESWHAT, ESWOW -- FEDucation -- IBM Design
ESWHO, ESWHAT, ESWOW -- FEDucation -- IBM Design
 
CGI::Prototype (NPW 2006)
CGI::Prototype (NPW 2006)CGI::Prototype (NPW 2006)
CGI::Prototype (NPW 2006)
 
Theming Drupal 7 - Meet your new best friend, render()
Theming Drupal 7 - Meet your new best friend, render()Theming Drupal 7 - Meet your new best friend, render()
Theming Drupal 7 - Meet your new best friend, render()
 
Advanced Drupal Views: Theming your View
Advanced Drupal Views: Theming your ViewAdvanced Drupal Views: Theming your View
Advanced Drupal Views: Theming your View
 
WordPress 3.4 Theme Customizer
WordPress 3.4 Theme CustomizerWordPress 3.4 Theme Customizer
WordPress 3.4 Theme Customizer
 
How to count money using PHP and not lose money
How to count money using PHP and not lose moneyHow to count money using PHP and not lose money
How to count money using PHP and not lose money
 
Jquery optimization-tips
Jquery optimization-tipsJquery optimization-tips
Jquery optimization-tips
 
Data::FormValidator Simplified
Data::FormValidator SimplifiedData::FormValidator Simplified
Data::FormValidator Simplified
 
Wp query
Wp queryWp query
Wp query
 
jQuery Performance Rules
jQuery Performance RulesjQuery Performance Rules
jQuery Performance Rules
 
Drawing images
Drawing imagesDrawing images
Drawing images
 
Beutiful javascript with coffeescript
Beutiful javascript with coffeescriptBeutiful javascript with coffeescript
Beutiful javascript with coffeescript
 

Viewers also liked

Viewers also liked (7)

jQuery Selectors
jQuery SelectorsjQuery Selectors
jQuery Selectors
 
Jquery.cheatsheet.1.4
Jquery.cheatsheet.1.4Jquery.cheatsheet.1.4
Jquery.cheatsheet.1.4
 
jQuery filters - Part 1
jQuery filters - Part 1jQuery filters - Part 1
jQuery filters - Part 1
 
JQuery selectors
JQuery selectors JQuery selectors
JQuery selectors
 
Selectors & Traversing
Selectors & TraversingSelectors & Traversing
Selectors & Traversing
 
Advanced JQuery Selectors
Advanced JQuery SelectorsAdvanced JQuery Selectors
Advanced JQuery Selectors
 
The Value of Search Engine Optimization
The Value of Search Engine OptimizationThe Value of Search Engine Optimization
The Value of Search Engine Optimization
 

Similar to Beyond the Final Frontier of jQuery Selectors

Drupal Development (Part 2)
Drupal Development (Part 2)Drupal Development (Part 2)
Drupal Development (Part 2)Jeff Eaton
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasminePaulo Ragonha
 
Turn your spaghetti code into ravioli with JavaScript modules
Turn your spaghetti code into ravioli with JavaScript modulesTurn your spaghetti code into ravioli with JavaScript modules
Turn your spaghetti code into ravioli with JavaScript modulesjerryorr
 
How to write code you won't hate tomorrow
How to write code you won't hate tomorrowHow to write code you won't hate tomorrow
How to write code you won't hate tomorrowPete McFarlane
 
Backbone js
Backbone jsBackbone js
Backbone jsrstankov
 
jQuery Data Manipulate API - A source code dissecting journey
jQuery Data Manipulate API - A source code dissecting journeyjQuery Data Manipulate API - A source code dissecting journey
jQuery Data Manipulate API - A source code dissecting journeyHuiyi Yan
 
Cheap frontend tricks
Cheap frontend tricksCheap frontend tricks
Cheap frontend tricksambiescent
 
Let jQuery Rock Your World
Let jQuery Rock Your WorldLet jQuery Rock Your World
Let jQuery Rock Your WorldMatt Gifford
 
Modern Web Development with Perl
Modern Web Development with PerlModern Web Development with Perl
Modern Web Development with PerlDave Cross
 
PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applicationselliando dias
 
Working with Javascript in Rails
Working with Javascript in RailsWorking with Javascript in Rails
Working with Javascript in RailsSeungkyun Nam
 
jQuery - 10 Time-Savers You (Maybe) Don't Know
jQuery - 10 Time-Savers You (Maybe) Don't KnowjQuery - 10 Time-Savers You (Maybe) Don't Know
jQuery - 10 Time-Savers You (Maybe) Don't Knowgirish82
 
Angular data binding by Soft Solutions4U
Angular data binding by Soft Solutions4UAngular data binding by Soft Solutions4U
Angular data binding by Soft Solutions4Usharsen
 
How to actually use promises - Jakob Mattsson, FishBrain
How to actually use promises - Jakob Mattsson, FishBrainHow to actually use promises - Jakob Mattsson, FishBrain
How to actually use promises - Jakob Mattsson, FishBrainCodemotion Tel Aviv
 
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you need
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you needDutch PHP Conference - PHPSpec 2 - The only Design Tool you need
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you needKacper Gunia
 
Real life-coffeescript
Real life-coffeescriptReal life-coffeescript
Real life-coffeescriptDavid Furber
 
JSGeneve - Backbone.js
JSGeneve - Backbone.jsJSGeneve - Backbone.js
JSGeneve - Backbone.jsPierre Spring
 
Tidy Up Your Code
Tidy Up Your CodeTidy Up Your Code
Tidy Up Your CodeAbbas Ali
 

Similar to Beyond the Final Frontier of jQuery Selectors (20)

Drupal Development (Part 2)
Drupal Development (Part 2)Drupal Development (Part 2)
Drupal Development (Part 2)
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
 
Turn your spaghetti code into ravioli with JavaScript modules
Turn your spaghetti code into ravioli with JavaScript modulesTurn your spaghetti code into ravioli with JavaScript modules
Turn your spaghetti code into ravioli with JavaScript modules
 
How to write code you won't hate tomorrow
How to write code you won't hate tomorrowHow to write code you won't hate tomorrow
How to write code you won't hate tomorrow
 
Backbone js
Backbone jsBackbone js
Backbone js
 
Django
DjangoDjango
Django
 
jQuery Data Manipulate API - A source code dissecting journey
jQuery Data Manipulate API - A source code dissecting journeyjQuery Data Manipulate API - A source code dissecting journey
jQuery Data Manipulate API - A source code dissecting journey
 
Cheap frontend tricks
Cheap frontend tricksCheap frontend tricks
Cheap frontend tricks
 
Let jQuery Rock Your World
Let jQuery Rock Your WorldLet jQuery Rock Your World
Let jQuery Rock Your World
 
Modern Web Development with Perl
Modern Web Development with PerlModern Web Development with Perl
Modern Web Development with Perl
 
PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applications
 
Working with Javascript in Rails
Working with Javascript in RailsWorking with Javascript in Rails
Working with Javascript in Rails
 
jQuery - 10 Time-Savers You (Maybe) Don't Know
jQuery - 10 Time-Savers You (Maybe) Don't KnowjQuery - 10 Time-Savers You (Maybe) Don't Know
jQuery - 10 Time-Savers You (Maybe) Don't Know
 
Angular data binding by Soft Solutions4U
Angular data binding by Soft Solutions4UAngular data binding by Soft Solutions4U
Angular data binding by Soft Solutions4U
 
Volt 2015
Volt 2015Volt 2015
Volt 2015
 
How to actually use promises - Jakob Mattsson, FishBrain
How to actually use promises - Jakob Mattsson, FishBrainHow to actually use promises - Jakob Mattsson, FishBrain
How to actually use promises - Jakob Mattsson, FishBrain
 
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you need
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you needDutch PHP Conference - PHPSpec 2 - The only Design Tool you need
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you need
 
Real life-coffeescript
Real life-coffeescriptReal life-coffeescript
Real life-coffeescript
 
JSGeneve - Backbone.js
JSGeneve - Backbone.jsJSGeneve - Backbone.js
JSGeneve - Backbone.js
 
Tidy Up Your Code
Tidy Up Your CodeTidy Up Your Code
Tidy Up Your Code
 

More from Alexander Shopov

Knots - the Lazy Data Transfer Objects for Dealing with the Microservices Craze
Knots - the Lazy Data Transfer Objects for Dealing with the Microservices CrazeKnots - the Lazy Data Transfer Objects for Dealing with the Microservices Craze
Knots - the Lazy Data Transfer Objects for Dealing with the Microservices CrazeAlexander Shopov
 
Нови приключения на преводачите
Нови приключения на преводачитеНови приключения на преводачите
Нови приключения на преводачитеAlexander Shopov
 
Bundling Packages and Deploying Applications with RPM
Bundling Packages and Deploying Applications with RPMBundling Packages and Deploying Applications with RPM
Bundling Packages and Deploying Applications with RPMAlexander Shopov
 
I Know Kung Fu - Juggling Java Bytecode
I Know Kung Fu - Juggling Java BytecodeI Know Kung Fu - Juggling Java Bytecode
I Know Kung Fu - Juggling Java BytecodeAlexander Shopov
 
Lifting The Veil - Reading Java Bytecode During Lunchtime
Lifting The Veil - Reading Java Bytecode During LunchtimeLifting The Veil - Reading Java Bytecode During Lunchtime
Lifting The Veil - Reading Java Bytecode During LunchtimeAlexander Shopov
 
Lifting The Veil - Reading Java Bytecode
Lifting The Veil - Reading Java BytecodeLifting The Veil - Reading Java Bytecode
Lifting The Veil - Reading Java BytecodeAlexander Shopov
 

More from Alexander Shopov (10)

700 Tons of Code Later
700 Tons of Code Later700 Tons of Code Later
700 Tons of Code Later
 
Knots - the Lazy Data Transfer Objects for Dealing with the Microservices Craze
Knots - the Lazy Data Transfer Objects for Dealing with the Microservices CrazeKnots - the Lazy Data Transfer Objects for Dealing with the Microservices Craze
Knots - the Lazy Data Transfer Objects for Dealing with the Microservices Craze
 
Нови приключения на преводачите
Нови приключения на преводачитеНови приключения на преводачите
Нови приключения на преводачите
 
In Vogue Dynamic
In Vogue DynamicIn Vogue Dynamic
In Vogue Dynamic
 
Bundling Packages and Deploying Applications with RPM
Bundling Packages and Deploying Applications with RPMBundling Packages and Deploying Applications with RPM
Bundling Packages and Deploying Applications with RPM
 
Oracle's Take On NoSQL
Oracle's Take On NoSQLOracle's Take On NoSQL
Oracle's Take On NoSQL
 
I Know Kung Fu - Juggling Java Bytecode
I Know Kung Fu - Juggling Java BytecodeI Know Kung Fu - Juggling Java Bytecode
I Know Kung Fu - Juggling Java Bytecode
 
Lifting The Veil - Reading Java Bytecode During Lunchtime
Lifting The Veil - Reading Java Bytecode During LunchtimeLifting The Veil - Reading Java Bytecode During Lunchtime
Lifting The Veil - Reading Java Bytecode During Lunchtime
 
Caching in HTTP
Caching in HTTPCaching in HTTP
Caching in HTTP
 
Lifting The Veil - Reading Java Bytecode
Lifting The Veil - Reading Java BytecodeLifting The Veil - Reading Java Bytecode
Lifting The Veil - Reading Java Bytecode
 

Recently uploaded

Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...panagenda
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 

Recently uploaded (20)

Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 

Beyond the Final Frontier of jQuery Selectors

  • 1. Beyond the Final Frontier of jQuery Selectors Alexander Shopov <ash@kambanaria.org>
  • 2. [ash@edge ~]$ whoami By day: Software Engineer at Cisco By night: OSS contributor Coordinator of Bulgarian Gnome TP Contacts: E-mail: ash@kambanaria.org Jabber: al_shopov@jabber.minus273.org LinkedIn: http://www.linkedin.com/in/alshopov SlideShare: http://www.slideshare.net/al_shopov Web: Just search “al_shopov”
  • 3. Please Learn And Share License: CC-BY v4.0
  • 4. Contents ● The Bold And the Beautiful ● Guiding Light ● As The World Turns
  • 5. The Bold And the Beautiful
  • 6. Bold! <style>.bold {font-weight: bold}</style> <div id="d" class="bold">This is bold</div> <script>jQuery(function (){ console.log(jQuery('#d').css('font-weight')); }); </script>
  • 7. Bold!! <style>.bold {font-weight: bold}</style> <div id="d" class="bold">This is bold</div> <script>jQuery(function (){ console.log(jQuery('#d').css('font-weight')); }); </script> Chrome/Safari/Opera bold
  • 8. Bold?? <style>.bold {font-weight: bold}</style> <div id="d" class="bold">This is bold</div> <script>jQuery(function (){ console.log(jQuery('#d').css('font-weight')); }); </script> Chrome/Safari/Opera bold IE11/Firefox 700
  • 9. Thus Spoke The Standards Value: normal | bold | bolder | lighter | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 Initial: normal Applies to: all elements Inherited: yes Percentage values: N/A CSS1 [CSS Level 1/CSS Level 2 (Revision 1)/ CSS Transitions/CSS Fonts Module Level 3] 100 200 300 400 500 600 700 800 900 - Thin Extra Light (Ultra Light) Light Normal Medium Semi Bold (Demi Bold) Bold Extra Bold (Ultra Bold) Black (Heavy) 100 ≤ 200 ≤ 300 ≤ 400 ≤ 500 ≤ 600 ≤ 700 ≤ 800 ≤ 900
  • 10. Beautiful There is difference between Italic and Oblique font shapes ● Do you know it? ●
  • 11. Beautiful Italics are stylized cursive writings – as if we write by hand. They have different shapes than roman/regular ● Obliques look like slanted roman/regular – poor man's italics ●
  • 12. The Three Graces – Roman/regular, Italic, Oblique
  • 13. How Can We Use Them With A Single Button?
  • 14. How Can We Use Them? Web Fonts! <style type="text/css"> @font-face { font-family: lmr; src: url(lmrtest-regular.otf); } @font-face { font-family: lmr; font-style: italic; src: url(lmrtest-italic.otf); } @font-face { font-family: lmr; font-style: oblique; src: url(lmrtest-oblique.otf); } </style> <div style="font-family:lmr"> <p style="font-style:normal"> Roman </p> <p style="font-style:italic"> Italic </p> <p style="font-style:oblique"> Oblique </p> </div>
  • 15. How Can We Find The Bold And The Beautiful? function isBold(el){ var w = jQuery(el).css('font-weight'); return ('bold' === w) || (400 < (+w)); } function isSlanted(el){ var s = jQuery(el).css('font-style'); return ('italic' === s) || ('oblique' === s) ; }
  • 16. Sorry Mario, Our Princess is in Another Castle ● ● ● We did not find the elements We can just check whether a particular element is what we are interested in So we use it like this and create functions time and again: jQuery('selector …').filter(function(i){ return isBold(i); });
  • 17. A Slight Improvement function bold4jQ(){ var w = jQuery(this).css('font-weight'); return ('bold' === w) || (400 < (+w)); } jQuery('selector …').filter(bold4jQ); function slanted4jQ(){ var s = jQuery(this).css('font-style'); return ('italic' === s) || ('oblique' === s); } jQuery('selector …').filter(slanted4jQ);
  • 18. (You Gotta) Fight For Your Right (to jQuery) ● ● ● Why do this imperatively and explicitly call time and agang the same functions? jQuery has its own selector engine, why not use it to accomplish our needs Let's be declarative – which is more readable? jQuery('selector …').filter(bold4jQ); jQuery('selector …').filter(slanted4jQ); jQuery('selector:bold'); jQuery('selector:slanted');
  • 20. This Is How We Do It jQuery.extend(jQuery.expr[':'], { bold: function(el) { var w = jQuery(el).css('font-weight'); return ('bold' === w) || (400 < (+w)); } }); jQuery('div:bold'); jQuery.extend(jQuery.expr[':'], { slanted: function(el) { var s = jQuery(el).css('font-style'); return ('italic' === s) || ('oblique' === s); } }); jQuery('#editor span.usr:slanted');
  • 21. Homework Asignments ● Find external links ● Find links that lead to ASPX or JSP pages directly ● Find divs with sizes above 42px ● Find spans that are block elements or divs that are inline ● The sky is the limit
  • 22. Is This All There Is? ● We are not limited to no args functions. The function we provide is called with 3 arguments. We can dispatch behaviour based on all of them /* returns boolean - whether given DOM * element matches matcher( /* single DOMElement from currenlty * matched set to check DOMElement, /* index of the current element in * in the matched set index, /* array of the split matching * sequence matches); * */ * */ * */ * */
  • 23. Positional Parameters Example Usage jQuery('selector…:font(14,400,italic)'); m = ['font', 'font', '', '14,400,italic'];
  • 24. Positional Parameters Example Usage jQuery('selector…:font(14,400,italic)'); m = ['font', 'font', '', '14,400,italic']; m[3] === '14,400,italic';
  • 25. Positional Parameters Example Usage jQuery('selector…:font(14,400,italic)'); m = ['font', 'font', '', '14,400,italic']; m[3] === '14,400,italic'; // split & coerce m[3] === '14,400,italic';
  • 26. Positional Parameters Example Usage jQuery.extend(jQuery.expr[':'], { font: function(el, i, m){ var a = m[3].split(','), // dispatch l = a.length, // dispatch j = jQuery(el), // cache p = ['size', 'weight', 'style'], z = 0; // index if(0 === l){return true;} if(3 < l){throw {name:'Funky', message:'Nuts?'};} // or return false and fail silently for(;z<l;++z){if(j.css('font-'+p[z])!=a[z]){return false;}} return true; }});
  • 27. Named Parameters Example Usage jQuery('selector…:font' + '(size>14,400<=weight,italic!=style,family!=Sans)' m = ['font', 'font', '', 'size>14,400<=weight,italic!=style,family!=Sans'
  • 28. Named Parameters Example Usage jQuery('selector…:font' + '(size>14,400<=weight,italic!=style,family!=Sans)' m = ['font', 'font', '', 'size>14,400<=weight,italic!=style,family!=Sans' m[3] === // what to do, what to do? 'size>14,400<=weight,italic!=style,family!=Sans'
  • 29. Named Parameters Example Usage 'size>14,400<=weight,italic!=style,family!=Sans'
  • 30. Named Parameters Example Usage // split, split, juggle & check 'size>14,400<=weight,italic!=style,family!=Sans'
  • 31. Named Parameters Example Usage // split, split, juggle & check 'size>14,400<=weight,italic!=style,family!=Sans' // split, juggle & check ['size>14','400<=weight','italic!=style','family!=Sans']
  • 32. Named Parameters Example Usage // split, split, juggle & check 'size>14,400<=weight,italic!=style,family!=Sans' // split, juggle & check ['size>14','400<=weight','italic!=style','family!=Sans'] [['size','>','14' ], ['400','<=','weight' ], ['italic','!=','style'], ['family','!=','Sans' ]] // juggle & check
  • 33. Named Parameters Example Usage // split, split, juggle & check 'size>14,400<=weight,italic!=style,family!=Sans' // split, juggle & check ['size>14','400<=weight','italic!=style','family!=Sans'] [['size','>','14' ], ['400','<=','weight' ], ['italic','!=','style'], ['family','!=','Sans' ]] [['family','!=','Sans' ['size' ,'>' ,'14' ['style' ,'!=','italic' ['weight','<=','400' // juggle & check ], ], ], ]] // check left as an // excercise for the // reader
  • 34. Named Parameters Example Usage Getting Jiggy With It m[3] === // be creative 'size>14,400<=weight,italic!=style,family!=Sans' 'size>14,400<=weight,italic!=style,family!=Sans'
  • 35. Named Parameters Example Usage Getting Jiggy With It m[3] === // be creative 'size>14,400<=weight,italic!=style,family!=Sans' 'size>14,400<=weight,italic!=style,family!=Sans' 'size>14,400<=weight,italic!=style,family!=Sans'. replace(/,/g,'&&') === ???
  • 36. Named Parameters Example Usage Getting Jiggy With It m[3] === // be creative 'size>14,400<=weight,italic!=style,family!=Sans' 'size>14,400<=weight,italic!=style,family!=Sans' 'size>14,400<=weight,italic!=style,family!=Sans'. replace(/,/g,'&&') === ??? "size>14&&400<=weight&&italic!=style&&family!=Sans"
  • 37. Looks familiar, doesnt' it? var expression = "size>14&&400<=weight&&italic!=style&&family!=Sans"; ● But what are size, weight, style, family? ● What about italic and Sans?
  • 38. But We Already Know That size: weight: style: family: j.css('font-size') j.css('font-weight') j.css('font-style') j.css('font-family') italic: 'italic', Sans: 'Sans'
  • 39. Why Didn't You Say So? var scope = { size: weight: style: family: j.css('font-size'), j.css('font-weight'), j.css('font-style'), j.css('font-family'), italic: 'italic', Sans: 'Sans'};
  • 40. Mojo!!! var r; with (scope){ r = eval (expression); } // PROFIT!!!
  • 41. Now That You Know How ● DON'T!!! ● Use to explore, you brave explorers. ● Use in production is misuse – will void your warranty, kill kittens and cause plague.
  • 42. So What Is The Catch? ● Quick to implement, experiment, POC; ● Piggyback on JavaScript as a host for the DSL; ● ● ● Hard to debug, with weird error messages in strange places – still we are in control of the scope template and this can be mitigated; Blocks browser's JS optimization engine (but we are not the only ones); Jslint will complain – we are treading in one of the the darkest places in the language.
  • 43. How Do You Say De-Groovie? How Do You Say De-Bug? jQuery('selector…:debug'); jQuery.extend(jQuery.expr[':'], { debug: function(el, i, m) { console.log("args: %o", arguments); console.log("m: %o", m); return true; } });
  • 44. The Power Of Their Source? The Crystal! https://github.com/jquery/jquery/blob/master/src/selector-sizzle.js define(["./core", "sizzle"], function( jQuery, Sizzle ) { jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; });
  • 45. As the World Turns
  • 46. Sizzle, Who the (BLEEP) is Sizzle? ● ● Sizzle: A pure-JavaScript CSS selector engine designed to be easily dropped in to a host library. Embedded in jQuery, MooTools, Dojo Version Supported browsers LOC Minified API jQuery 1.10.2 IE6+, FF(Current-1)+, Chrome(Current≈10k 1)+, Safari 5.1+, Opera 12.1x, (Current-1)+ ≈93kB Vast jQuery 2.0.3 IE9+, FF(Current-1)+, Chrome(Current≈9k 1)+, Safari 5.1+, Opera 12.1x, (Current-1)+ ≈84kB Vast Sizzle IE6+, FF3.0+, Chrome 5+, Safari 3+, Opera 9+ ≈18kB Tiny 1.10.1x ≈2k
  • 47. Sizzle API – part 1 /* returns boolean - whether given DOM * element matches selector * If available uses native matchesSelector Sizzle.matchesSelector( /* DOMElement to check DOMElement, /* String – CSS Selector selector); * * */ */ */
  • 48. Sizzle API – part 2 /* returns Array of the elements that match * the selector Sizzle.matches( /* String – CSS Selector selector, /* Array of DOMElements elements); * */ */ */
  • 49. Sizzle API – part 3 /* Return nodes that match selector * [starting from the context node] * as an array [or added to the provided * array-like object] Sizzle( /* String – CSS Selector selector, /* Optional: DOMElement|DOMDocument * Default: Current document * Node to start the search from context, /* Optional: Array-like object to * add elements to * eg.: jQuery() obj * Default: Create new array results); */ */ * * */ * * * */
  • 50. That's All Folks! This was the whole public API!
  • 51. Do It Very Slowly (True Lies) ● ● document.querySelectorAll is very fast and meddles with our meddling Get rid of it! document.querySelectorAll = null; // or any falsy // why not? delete document.querySelectorAll;
  • 52. Alien ● querySelectorAll (as well as querySelector) comes from elsewhere – from the prototype world ● Prototype world is wilder that the West! ● Object.getPrototypeOf() – IE, Chrome, Firefox ● {}.__proto__ – Firefox, Chome
  • 53. Alien 2 – IE 10 querySelectorAll WORKS: = null; FAILS: delete Node Protoype document Document Protoype Window window null Object
  • 54. Alien 4 – Firefox querySelectorAll WORKS: = null; FAILS: delete document HTML Document Prototype Document Prototype window null Node Prototype [Window Prototype] Event Target Prototype Object
  • 55. Alien 3 – Chrome querySelectorAll null WORKS: = null; FAILS: delete Node document HTML Document Document Window window Event Target Object
  • 56. Alien 4 – Firefox querySelectorAll WORKS: = null; FAILS: delete document HTML Document Prototype Document Prototype window null Node Prototype [Window Prototype] Event Target Prototype Object
  • 57. What We Used Thus Far // Thus far we actually extended Sizzle.selectors.pseudos; //jQuery does some magic to ease using Sizzle.selectors.createPseudo(function(){});
  • 58. Where Next // Matches parts of selector (as string) // divides in parts Sizzle.selectors.match.NAME = new RegExp('...'); Sizzle.selectors.find.NAME = function( // what was matched above match, // element to start search from context, // whether doc is XML/HTML IsXML ) {}; // regex of orders, add |NAME to it Sizzle.selectors.order;
  • 59. Where Next // quick prefilter, eg: remove all attributes or // elements based on a quick decision Sizzle.selectors.preFilter.NAME = function( match ) {}; // slow filter invoked after the one above (if ∃) // real evaluation Sizzle.selectors.filter.NAME = function(element, m1, m2, m3 ) {};
  • 60. Sizzle is extensible ● No extension tests in test harness; ● Dragons around the corers, YMMV; ● ● Looooooooooooooooo + ooooooooooooo + oooo + oooooo + oooooooo + oooooo + ooooooooooooooooooooooooooo + oooooooo + ooooooooooo + ooooong regular expressions; Actual regular expressions are longer.