标记:
<ul>
<li role="presentation" class="active">
<a href="#1" aria-controls="1" role="tab">How to Install for iPad</a>
</li>
<li role="presentation">
<a href="#2" aria-controls="2" role="tab">How to Install for Mac</a>
</li>
<li role="presentation">
<a href="#3" aria-controls="3" role="tab">How to Install for PC</a>
</li>
</ul>
当我使用 document.querySelectorAll(&#39; [role =&#34; presentation&#34;]&#39;); 时,结果是数组 [li.active,LI,LI]
如何删除.active类并使用简单的JS w / o JQuery将其附加到这些li的任何其他类中?更简单的方法?
答案 0 :(得分:7)
试试这个:
// remove active class from all elements
document.querySelectorAll('[role="presentation"]').forEach(function (el){
el.classList.remove("active");
});
// add class 'active' to last element
document.querySelectorAll('[role="presentation"]:last-of-type')[0].classList.add("active")
注意:
答案 1 :(得分:1)
您可以尝试这样的事情:
var ele = document.querySelectorAll('[role="presentation"]');
ele[0].classList.remove("active"); //Remove active class for first element
ele[ele.length- 1].classList.add("active"); //Apply active class for last element
console.log(ele)
答案 2 :(得分:1)
var eleLi = document.querySelectorAll('[role="presentation"]');
for (var i = 0; i < eleLi.length; i++) {
//remove class active
eleLi[i].classList.remove('active');
}
//x is an index of li that you want to add the class. Such as 0,1,2
var x = eleLi.length - 1;
//add class active
eleLi[x].classList.add('active');