Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery selector that simulates :starts-with or :ends-with for searching text?

If you look at the selectors list on the jQuery website, there are selectors for starts-with and ends-with on attributes. There's also a :contains selector for searching text:

alert( $("div").find("span:contains(text)").html() );

Does jQuery have an implementation for searching strings using starts-with or ends-with?

FYI: I need to search through an XML object.

like image 575
user717236 Avatar asked Feb 09 '12 15:02

user717236


People also ask

Which is the jQuery selector function used for selecting the elements?

The #id Selector The jQuery #id selector selects an HTML element based on the element id attribute. Following is a simple syntax of a #id selector: $(document).

What is find () in jQuery?

The find() is an inbuilt method in jQuery which is used to find all the descendant elements of the selected element. It will traverse all the way down to the last leaf of the selected element in the DOM tree. Syntax: $(selector).find()


1 Answers

Not by default as far as I know, but you can add your own pseudo-selectors through $.expr[":"]: http://jsfiddle.net/h6KYk/.

$.extend($.expr[":"], {
    "starts-with": function(elem, i, data, set) {
        var text = $.trim($(elem).text()),
            term = data[3];

        // first index is 0
        return text.indexOf(term) === 0;
    },

    "ends-with": function(elem, i, data, set) {
        var text = $.trim($(elem).text()),
            term = data[3];

        // last index is last possible
        return text.lastIndexOf(term) === text.length - term.length;
    }
});
like image 165
pimvdb Avatar answered Sep 20 '22 05:09

pimvdb