JavasSript(无 jQuery)查找多个类并向每个类添加新类

我可以找到使用 jQuery 的示例,但找不到如何在纯 JavaScript 中执行此操作的答案。


是否可以使用 JavaScript 将这两个类循环组合起来以简化代码。我将为我正在进行的项目完成大约 20 节课。


var srtClass1 = document.getElementsByClassName('class1');

for(var i = 0; i < srtClass1.length; i++) {

    srtClass1[i].classList.add('newClass');

    srtClass1[i].classList.remove('class1');

}

var srtClass2 = document.getElementsByClassName('class2');

for(var i = 0; i < srtClass2.length; i++) {

    srtClass2[i].classList.add('newClass');

    srtClass2[i].classList.remove('class2');

}


ITMISS
浏览 152回答 3
3回答

慕尼黑8549860

你可以尝试这样的事情。您只需要用要删除的所有类填充数组。var classes = ['.class1', '.class2', '.class3'];var elements = document.querySelectorAll(classes.join(','));for (let element of elements) {&nbsp; element.classList.add('newClass');&nbsp; &nbsp;&nbsp;&nbsp; for (let className in classes) {&nbsp; &nbsp; element.classList.remove(className);&nbsp; &nbsp;&nbsp;&nbsp; }}.box {&nbsp;&nbsp; display: block;&nbsp; width: 100%;&nbsp; height: 20px;&nbsp; margin: 0 0 20px 0;}.class1 { background: red; }.class2 { background: green; }.class3 { background: blue; }.newClass { background: yellow; }<div class="box class1"></div><div class="box class2"></div><div class="box class3"></div>

慕工程0101907

您可以合并 2 个集合:var srtClass1 = [...document.getElementsByClassName('class1'), ...document.getElementsByClassName('class2')];for(var i = 0; i < srtClass1.length; i++) {&nbsp; &nbsp; srtClass1[i].classList.add('newClass');&nbsp; &nbsp; srtClass1[i].classList.remove('class1');&nbsp; &nbsp; srtClass1[i].classList.remove('class2');}你可以使用高阶函数:[...document.getElementsByClassName('class1'), ...document.getElementsByClassName('class2')].forEach( el => {&nbsp; &nbsp; el.classList.add('newClass');&nbsp; &nbsp; el.classList.remove('class1');&nbsp; &nbsp; el.classList.remove('class2');});甚至更好(因为classList.remove支持多个参数):[...document.getElementsByClassName('class1'), ...document.getElementsByClassName('class2')].forEach( el => {&nbsp; &nbsp; el.classList.add('newClass');&nbsp; &nbsp; el.classList.remove('class1', 'class2');});或者,如果您愿意,可以使用querySelectorAll:document.querySelectorAll('.class1, .class2').forEach(el => {&nbsp; &nbsp; el.classList.add('newClass');&nbsp; &nbsp; el.classList.remove('class1', 'class2');});

牛魔王的故事

也许尝试制作一个类列表,然后迭代它:function changeClasses() {&nbsp; let classNames = ['class1', 'class2'];&nbsp; classNames.forEach(className => {&nbsp; &nbsp; const node = document.querySelector(`.${className}`);&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; if (node != null) {&nbsp; &nbsp; &nbsp; node.classList.add('newClass');&nbsp; &nbsp; &nbsp; node.classList.remove(className);&nbsp; &nbsp; }&nbsp; });}.class1 {&nbsp; color: green;}.class2 {&nbsp; color: blue;}.newClass {&nbsp; color: red;}<body>&nbsp; <div class="class1">class1</div>&nbsp; <div class="class2">class2</div>&nbsp;&nbsp;&nbsp; <button onclick="changeClasses()">Change classes</button></body>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript