javascript - Removing specific classes from all div elements of certain format -
i remove classes starting nf-
jsfiddle https://jsfiddle.net/zapjelly/fda3lm84/11/
i have following html/js:
var nfclasses = document.queryselectorall('.custom-nf [class*="nf-"]'); array.prototype.map.call(nfclasses, function(elem) { array.prototype.map.call(elem.classlist, function(classstr) { if (classstr.match(/^nf\-/)) elem.classlist.remove(classstr); }); });
<p>remember inspect element on input below</p> <div class="custom-nf"> <div class="input nf-input-outer nf-validation"> <div class="nf-container"> <div class="nf-outer nf-outer-input nf-outer-validation"> <div class="nf-middle"> <div class="nf-inner"> <label for="dummy" class="nf-label"></label> <input id="dummy" type="text" class="nf-input"> </div> </div> </div> </div> </div> </div>
as stated mdn, .classlist
property returns live domtokenlist of class attributes of element. key point list live, means remove classes, inadvertently skipping on of other classes while iterating on them.
based on code provided, create copy of class list no longer live. can calling .slice()
method:
var nfclasses = document.queryselectorall('.custom-nf [class*="nf-"]'); array.prototype.foreach.call(nfclasses, function(element) { var classlistcopy = array.prototype.slice.call(element.classlist); classlistcopy.foreach(function(classname) { if (classname.match(/^nf\-/)) { element.classlist.remove(classname); } }); });
alternatively, iterate on classes backwards. in doing so, none of classes skipped:
var nfclasses = document.queryselectorall('.custom-nf [class*="nf-"]'); array.prototype.foreach.call(nfclasses, function(element) { (var = element.classlist.length; >= 0; i--) { if (element.classlist[i] && element.classlist[i].match(/^nf\-/)) { element.classlist.remove(element.classlist[i]); } } });
a third option use regular expression replace classes:
var nfclasses = document.queryselectorall('.custom-nf [class*="nf-"]'); array.prototype.foreach.call(nfclasses, function(element) { element.classname = element.classname.replace(/\bnf-\s+\b/g, '').trim(); });
Comments
Post a Comment