3 回答

TA貢獻1818條經(jīng)驗 獲得超11個贊
你可以嘗試這樣的事情。您只需要用要刪除的所有類填充數(shù)組。
var classes = ['.class1', '.class2', '.class3'];
var elements = document.querySelectorAll(classes.join(','));
for (let element of elements) {
element.classList.add('newClass');
for (let className in classes) {
element.classList.remove(className);
}
}
.box {
display: block;
width: 100%;
height: 20px;
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>

TA貢獻1887條經(jīng)驗 獲得超5個贊
您可以合并 2 個集合:
var srtClass1 = [...document.getElementsByClassName('class1'), ...document.getElementsByClassName('class2')];
for(var i = 0; i < srtClass1.length; i++) {
srtClass1[i].classList.add('newClass');
srtClass1[i].classList.remove('class1');
srtClass1[i].classList.remove('class2');
}
你可以使用高階函數(shù):
[...document.getElementsByClassName('class1'), ...document.getElementsByClassName('class2')].forEach( el => {
el.classList.add('newClass');
el.classList.remove('class1');
el.classList.remove('class2');
});
甚至更好(因為classList.remove支持多個參數(shù)):
[...document.getElementsByClassName('class1'), ...document.getElementsByClassName('class2')].forEach( el => {
el.classList.add('newClass');
el.classList.remove('class1', 'class2');
});
或者,如果您愿意,可以使用querySelectorAll:
document.querySelectorAll('.class1, .class2').forEach(el => {
el.classList.add('newClass');
el.classList.remove('class1', 'class2');
});

TA貢獻1830條經(jīng)驗 獲得超3個贊
也許嘗試制作一個類列表,然后迭代它:
function changeClasses() {
let classNames = ['class1', 'class2'];
classNames.forEach(className => {
const node = document.querySelector(`.${className}`);
if (node != null) {
node.classList.add('newClass');
node.classList.remove(className);
}
});
}
.class1 {
color: green;
}
.class2 {
color: blue;
}
.newClass {
color: red;
}
<body>
<div class="class1">class1</div>
<div class="class2">class2</div>
<button onclick="changeClasses()">Change classes</button>
</body>
添加回答
舉報