Saturday, June 28, 2014

Extending jQuery Selectors

A small source of frustration for jQuery developers is the :contains() selector doesn't have a startswith option. A selector indicating elements that start with a string is extremely helpful, but the good folks at jQuery central haven't given us one.

Good news!  We can easily write one ourselves.

$.extend($.expr[":"], {
    "startswith": function(elem, i, data, set) {
        var txt = $.trim($(elem).text());
        var term = data[3];
        return txt.indexOf(term) === 0;
    }
}); 
Simply place this into a convenient location (after your jQuery script) and you'll be able to use ":startswith"

For example: to find all the
s that have "blah" as their inner text, just do this:

    $('div:startswith("blah")')...

Here's a jsfiddle to use as a quick demo: http://jsfiddle.net/richbuff/43AtR/

Hope this helps!