Remove the entire class from an element matching a specific format using jQuery

I asked a similar question before, but my wording provided correctly presented answers, but not to the question that I was actually trying to answer :) In an attempt not to confuse the SO lists, I posted this question separately.

Given the HTML below, what is the most convenient way to remove all classes from # item_3 that starts with "child_"?

The solution should be able to save the "stays_put" class and not affect any of the other elements of the list.

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

The question I originally asked can be found here. Using Reg Ex in jQuery Selection

+3
source share
2 answers

, , class, :

$('#item_3').attr('class', function() {
    return $.trim($(this).attr('class').replace(/child_\S+/g, ''));
});

child_, , class . /child_\S+/g child_, , .

jsFiddle preview

+3

split jQuery.each:

var classes = $('#item_3').attr('class').split(' ');
$.each( classes, function( idx, val ) {
   if( val.indexOf('child_') === 0 ) {
      $('#item_3').removeClass( val );
   }
});
0

All Articles