Sep 18th 2012 × Extend Slick pseudo selector to find data-attributes
This is a relatively simple idea. Select elements with data-attributes that match a pattern, for example, div[data-media-*]. The problem is, CSS selectors don;t allow you to wildcard attributes themselves so we need to be creative.
We will extend the Slick selector engine with a data pseudo selector, which will look at the outerHTML of the element and find a match for the attrbute, starting with data-value*:
Slick.definePseudo('data', function(value){
// wildcard data-startswith search
var outer = this.outerHTML || new XMLSerializer().serializeToString(this);
return outer.test('data-' + value);
});
console.log($$("div:data(media-)")); // return all divs with data-media-* attribute
This is it at a first reading. Now, given how performance is important, especially if used on a large DOM without a qualified selector, let’s see if we can optimise it by using a closure where the setup takes place. We will cache the strings we reuse so no new strings need to be made for each element passed to Slick, as well as a single instance of the XMLSerializer, used by the fallback when outerHTML is not available. We also go to Array.join instead of string concatenate for small gains in IE6/7/8
(function(){
// cache reusable strings
var data = 'data',
hyphen = '-',
// set the fallback via XMLSerializer, if no outerHTML (eg. FF 2 - 10)
XS = this.XMLSerializer && new XMLSerializer();
Slick.definePseudo(data, function(value){
return (this.outerHTML || XS.serializeToString(this)).test([data, value].join(hyphen));
});
}());
Happy coding.




