Skip to content

Commit

Permalink
add .remove(regexp) support
Browse files Browse the repository at this point in the history
  • Loading branch information
tj committed Jan 30, 2013
1 parent a9532b4 commit b4b5957
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 7 deletions.
11 changes: 7 additions & 4 deletions Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,10 @@ $ component install component/classes

```js
var classes = require('classes');
classes(el).add('foo').toggle('bar');
classes(el)
.add('foo')
.toggle('bar')
.remove(/^item-\d+/);
```

## API
Expand All @@ -24,7 +27,7 @@ classes(el).add('foo').toggle('bar');

### .remove(class)

Remove `class`.
Remove `class` name or all classes matching the given regular expression.

### .toggle(class)

Expand All @@ -38,6 +41,6 @@ classes(el).add('foo').toggle('bar');

Return an array of classes.

## License
## License

MIT
MIT
34 changes: 32 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,12 @@ var index = require('indexof');

var re = /\s+/;

/**
* toString reference.
*/

var toString = Object.prototype.toString;

/**
* Wrap `el` in a `ClassList`.
*
Expand Down Expand Up @@ -59,14 +65,20 @@ ClassList.prototype.add = function(name){
};

/**
* Remove class `name` when present.
* Remove class `name` when present, or
* pass a regular expression to remove
* any which match.
*
* @param {String} name
* @param {String|RegExp} name
* @return {ClassList}
* @api public
*/

ClassList.prototype.remove = function(name){
if ('[object RegExp]' == toString.call(name)) {
return this.removeMatching(name);
}

// classList
if (this.list) {
this.list.remove(name);
Expand All @@ -81,6 +93,24 @@ ClassList.prototype.remove = function(name){
return this;
};

/**
* Remove all classes matching `re`.
*
* @param {RegExp} re
* @return {ClassList}
* @api private
*/

ClassList.prototype.removeMatching = function(re){
var arr = this.array();
for (var i = 0; i < arr.length; i++) {
if (re.test(arr[i])) {
this.remove(arr[i]);
}
}
return this;
};

/**
* Toggle class `name`.
*
Expand Down
10 changes: 9 additions & 1 deletion test/classes.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,14 @@ describe('classes(el)', function(){
})
})

describe('.remove(regexp)', function(){
it('should remove matching classes', function(){
el.className = 'foo item-1 item-2 bar';
classes(el).remove(/^item-/);
assert('foo bar' == el.className);
})
})

describe('.toggle(class)', function(){
describe('when present', function(){
it('should remove the class', function(){
Expand Down Expand Up @@ -84,4 +92,4 @@ describe('classes(el)', function(){
assert(true === classes(el).has('there'));
})
})
})
})

0 comments on commit b4b5957

Please sign in to comment.