javascript 如何通过'role'属性选择元素并使用vanilla JS按类过滤?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46648761/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to select element by 'role' attribute and filter by class with vanilla JS?
提问by mixa_ru
Markup:
标记:
<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>
When I use document.querySelectorAll('[role="presentation"]');the result is array [li.active,li,li]
当我使用document.querySelectorAll('[role="presentation"]'); 结果是数组 [li.active,li,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?
如何删除 .active 类并将其附加到任何其他 li 使用纯 JS w/o JQuery 以更简单的方式?
回答by Anton Vovchenko
Try this:
试试这个:
// 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")
Notes:
笔记:
- 'classList' will not work in IE9;
- I think you have to modify adding class row, depending on your needs.
- 'classList' 在 IE9 中不起作用;
- 我认为您必须根据您的需要修改添加类行。
回答by Phani Kumar M
You can try something like this:
你可以尝试这样的事情:
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)
回答by pompom
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');

