如何通过“角色"属性选择元素并使用香草JS按类过滤? [英] How to select element by 'role' attribute and filter by class with vanilla JS?
本文介绍了如何通过“角色"属性选择元素并使用香草JS按类过滤?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
标记:
<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('[role ="presentation"]'); 时,结果为数组 [li.active,li,li]
如何删除.active类并将其附加到使用普通JS而不使用JQuery的其他li中,这是最简单的方法?
How can I remove .active class and attach it to any other of these li with plain JS w/o JQuery the more simplest way?
推荐答案
尝试一下:
// 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")
注意:
- 'classList'在IE9中不起作用;
- 我认为您必须根据需要修改添加类的行.
这篇关于如何通过“角色"属性选择元素并使用香草JS按类过滤?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文