javascript - Removing all classes starting with string -
i have following html:
<div class="cols someclass"></div> <!--like cols1, cols2, etc..--> <div class="columns someclass"></div> <!--like columns1, columns2, etc...--> <div class="col-1 someclass"></div> <!--like col-2, col-3,etc...--> <div class="column-1 someclass"></div> <!--like column-2, column-3, etc...-->
how remove classes starting "col"
?
i believe there no jquery magic this, here's solution:
$('[class*=col]').each(function() { this.classname = $.grep(this.classname.split(' '), function(el) { return !/^col/.test(el); }).join(' '); });
basically, selects elements have col
in classes , iterate on them, iterating on classes , removing begin col
.
or without regex:
$('[class*=col]').each(function() { this.classname = $.grep(this.classname.split(' '), function(cl) { return cl.lastindexof('col', 0); }).join(' '); });
using modified version of answer. lastindexof
return 0
if class starts col
falsy value , grep
remove it. if class not begin col
, -1
returned truthy value. can use return cl.lastindexof('col', 0) !== 0;
bit readability well.
or regex only:
$('[class*=col]').each(function() { this.classname = this.classname.replace(/(^| )col[^ ]*/g, ''); });
matches col
@ beginning of string or after space, removes leading characters space or end of string.
referece
jquery.grep
- finds elements of array satisfy filter function. original array not affected.element.classname
- gets , sets value ofclass
attribute of specified element.
of course, selector not optimal - if element has foocol
$('[class*=col]')
select it, $.grep
/regex not remove not begin col
. can't think of better selector (there's no attribute selector select value beginning partial string in space-separated list afaik), nevertheless should suffice fine.
Comments
Post a Comment