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

前端 未结 3 554
星月不相逢
星月不相逢 2021-02-06 08:48

Markup:

相关标签:
3条回答
  • 2021-02-06 09:27

    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.
    0 讨论(0)
  • 2021-02-06 09:30

    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)
    
    0 讨论(0)
  • 2021-02-06 09:39
    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'); 
    
    0 讨论(0)
提交回复
热议问题