Alex Rivera | Logout

jQuery - extract class name that 'starts with' prefix

Asked 2013-06-28T14:56:22.780
19

My items have the following classes:

<div class="class-x some-class-1 other-class"></div>
<div class="some-class-45 class-y"></div>
<div class="some-class-123 something-else"></div>

I'm wondering if there is an easy way to:

  1. Grab only all classes with some-class- prefix.
  2. Remove them from each element.
  3. Have their names (not corresponding DOM elements) in a variable?

I can easily select such elements with jQuery( "div[class^='some-class-'], div[class*=' some-class-']" ) but how its class name could be extracted with the shortest and the most readable code to a variable (can be some global object)?

Edit
Report

1 Answer

4

You could loop through all the elements, pull the class name using a regular expression, and store them in an array:

var classNames = [];
$('div[class*="some-class-"]').each(function(i, el){
    var name = (el.className.match(/(^|\s)(some\-class\-[^\s]*)/) || [,,''])[2];
    if(name){
        classNames.push(name);
        $(el).removeClass(name);
    }
});
console.log(classNames);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="class-x some-class-1 other-class"></div>
<div class="some-class-45 class-y"></div>
<div class="some-class-123 something-else"></div>

answered 2013-06-28T15:05:06.260

Your Answer