Friday, July 15, 2011

My custom jQuery selector for finding elements who have a text that begin with some string

My jQuery custom selector code:
$.expr[':'].textBeginWith = function (obj, index, meta) {
var $this = $(obj);
var subString = $this.text().substring(0, meta[3].length);

return (subString.toLowerCase() == (meta[3]).toLowerCase());
};

Usage example:
var elements = $('a:textBeginWith("My demo")');

As a result we will have selected all "a" elements whit "My demo" text at the beggining of the sentense.

Why do I need this code, well, the closest selector which will find all "a" elements with "My demo" text inside is "contains", BUT, contains will find any substring in sentence, not only at the beggining.