从特定格式的所有div元素中删除特定类

时间:2016-01-21 02:52:59

标签: javascript html css

我想删除所有以nf -

开头的课程

Console image

的jsfiddle https://jsfiddle.net/zapjelly/fda3Lm84/11/

我有以下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 to inspect element on the 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>

2 个答案:

答案 0 :(得分:1)

正如MDN所述,.classList property会返回该元素的类属性的实时 DOMTokenList。关键点是列表是实时,这意味着当您删除类时,在迭代它们时无意中跳过了其他一些类。

根据您提供的代码,您只需创建类列表的副本,使其不再存在。您可以通过调用.slice()方法来执行此操作:

Updated Example

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);
    }
  });
});

或者,您也可以向后迭代这些类。这样做,将不会跳过任何类:

Updated Example

var nfClasses = document.querySelectorAll('.custom-nf [class*="nf-"]');
Array.prototype.forEach.call(nfClasses, function(element) {
  for (var i = element.classList.length; i >= 0; i--) {
    if (element.classList[i] && element.classList[i].match(/^nf\-/)) {
      element.classList.remove(element.classList[i]);
    }
  }
});

第三种选择是使用正则表达式来替换类:

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();
});

答案 1 :(得分:0)

更新内部循环以按照建议切片并立即工作

https://jsfiddle.net/zapjelly/fda3Lm84/12/

var nfClasses = document.querySelectorAll('.custom-nf [class*="nf-"]');

Array.prototype.map.call(nfClasses,
    function(elem){
    Array.prototype.slice.call(elem.classList).map(
        function(classStr){
            if(classStr.match(/^nf\-/)) elem.classList.remove(classStr);
        })
  });