How to select element by 'role' attribute and filter by class with vanilla JS?

怎甘沉沦 提交于 2020-12-28 21:07:56

问题


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]

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?


回答1:


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.



回答2:


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)



回答3:


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'); 


来源:https://stackoverflow.com/questions/46648761/how-to-select-element-by-role-attribute-and-filter-by-class-with-vanilla-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!