Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we use a regex with a common jquery query? [duplicate]

Tags:

jquery

I would like to affect all my elements containing a class almost similar, i could iterate and use the iterator to do the job, but i am wondering if we could use a regex in this case:

$('.player').removeClass('player-1 player-2 player-3'); //player-n

Can the jQuery removeClass (and globaly the jquery methods which affects the DOM) treat a regex here ?

I am trying this:

$('.player').removeClass('/player-[0-9]+/');

The regex match i have tested it here, but it doesn't work on my DOM, does jQuery support the regex in this case?

like image 353
Ludo Avatar asked Oct 22 '22 06:10

Ludo


2 Answers

You could use any css selector which are kindof a regex.

http://api.jquery.com/category/selectors/

in your case it would be

$("[class^='player-']")

or

$("[class|='player']")

like image 131
mercsen Avatar answered Oct 24 '22 18:10

mercsen


You can use filter like this

var elements = $('.player').filter(function() {
    return this.className = this.className.replace(/player-[0-9]+/, '');
});

Fiddle

like image 42
iConnor Avatar answered Oct 24 '22 17:10

iConnor