alexmngn
alexmngn

Reputation: 9597

jQuery selector using regex (or something else)

I need to select an attribute in my code that match a string+number in the class name, using jQuery

What I need to do is to match something like that:

var myVar = 'item';
$('#id [class="'+myVar+'\d+"]');

My code contain other classes starting by "item" as well, so I can't use the selector class^="item"

I found out different things on Internet, but nothing that match perfectly my requirement.

I found the jQuery extension ":regex" but I'm not allowed to use it. http://james.padolsey.com/javascript/regex-selector-for-jquery/

I found the use of "filter" as a function but this is horrible for the performance jQuery filter selector, is this right?

I tried to do something but it's not even working:

$('#id *').filter(function() {
   return this.className.match("/"+myVar+"\d/");
});

Do you have some better suggestions?

Thanks.

Upvotes: 1

Views: 426

Answers (2)

acdcjunior
acdcjunior

Reputation: 135762

How about:

$('#id [class*=' + myVar + ']').filter(function() {
   return this.className.match(new RegExp('(^|\\s)' + myVar + '\\d+(\\s|$)'));
});

Check jsfiddle demo here.

The selector picks every descendant element of #id with myVar in a class name. Finally it filters them, leaving only those who have myVar followed by one or more of digits as the name of one of its classes.

Note: You probably aready know that, but it is worth warning anyway: you must prevent myVar from having chars with special meaning to selectors (which would mess the [class*=' + myVar + ']' selector) and to regexes (such as the string '[a-z]', which would make the regex match a range instead of the literal '[a-z]' -- in this case, it should be escaped, as '\[a-z\]').

Upvotes: 1

Daniel Imms
Daniel Imms

Reputation: 50189

No you can't use \d with CSS/jQuery selectors.

I suggest you split the number out into another attribute like data-number or something. This way you can target the class easily and efficiently and still have the number available.

<span class="my-class" data-number="1"></span>
<span class="my-class" data-number="6"></span>
<span class="my-class" data-number="10"></span>

jQuery example

$.each($('my-class'), function () {
    $(this).attr('data-number');
});

As @Asad mentions they can also be selected using $('.my-class[data-number="1"]').

Upvotes: 2

Related Questions