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

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.

Leave a Comment