Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - has class that starts with

What would be the best way to get all divs that have any class that starts with input? In other words, a and b should be returned from what's below, but not c.

<div id="a" class="input1 foo"></div>
<div id="b" class="foo input2"></div>
<div id="c" class="xinput3 foo"></div>

The ostensible way, which surprisingly was accepted here, is to do $("div[class^='input']"); but of course that misses b. And of course $("div[class*='input']"); will give a false positive on c.

The best I could come up with was this monstrosity

function getAllInputDivs() {
    return $("div").filter(function (i, currentDiv) {
        return $.grep($(currentDiv).attr("class").split(" "), function (val) {
            return val.substr(0, "input".length) === "input";
        }).length > 0;
    });
}

Is there a cleaner way? Here's a working fiddle of the above

like image 612
Adam Rackis Avatar asked Dec 20 '11 17:12

Adam Rackis


1 Answers

You can create your own expression in jQuery

$.expr[':'].hasClassStartingWithInput = function(obj){
  return (/\binput/).test(obj.className);
};

and you can retrieve those div with

$('div:hasClassStartingWithInput');

a JsFiddle Example: http://jsfiddle.net/7zFD6/


Edit: you could also use a parameter (without hardcoding the class name inside the function identifier) in this way

$.expr[':'].hasClassStartingWith = function(el, i, selector) {
  var re = new RegExp("\\b" + selector[3]);
  return re.test(el.className);
}

new example on http://jsfiddle.net/pMepk/1/

like image 120
Fabrizio Calderan Avatar answered Sep 24 '22 03:09

Fabrizio Calderan