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! 

3 comments:

  1. Nicely you explained everything in your article. Thanks for your information; this is nice and helpful… Definitely going to share this article to my friends.
    Germany VPS Hosting

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. Hello,
    I appreciate your blogs.
    It's a Nice blog Thanks for sharing. Will definitely try.
    Get best USA VPS Hosting
    service for your website.

    ReplyDelete