Using Reg Ex in jQuery Selection

I'm looking for a convenient way to use jQuery to remove all classes from an object that matches a specific format. This seems natural to Reg Ex, but I can't find any jQuery documentation supporting them in selectors. I figured StackOverflow would provide a faster solution.

Given the HTML below, what is the most convenient way to remove any class that starts with "child_"?

I don't need a solution to enable Reg Ex, it's just what seems natural given the problem. Any clean jQuery solution will work.

<ul id="list"> <li class="child_1 child_12">Item 1</li> <li class="child_4 child_6">Item 2</li> <li class="child_3 child_1 stays_put">Item 3</li> </ul> 

EDIT: I have to clarify that the goal is to remove the class, not the element. When the code is executed, all the elements of the list should still be there, but with the removal of the classes. Upon completion, it should look as follows.

 <ul id="list"> <li class="">Item 1</li> <li class=">Item 2</li> <li class="stays_put">Item 3</li> </ul> 
+4
source share
1 answer

I believe that this is what you want. It finds each element with child_ in the class name, and then removes only those classes with child_

Live demo

 var partial = /^child_/g; $('[class*=child_]').each(function(){ var classes = $(this).attr('class').split(' '); for(var i=0; i< classes.length;i++){ if(classes[i].match(partial)){ $(this).removeClass(classes[i]); } } }); 
+3
source

Source: https://habr.com/ru/post/1343835/


All Articles