【问题标题】:How to select element by 'role' attribute and filter by class with vanilla JS?如何通过'role'属性选择元素并使用vanilla JS按类过滤?
【发布时间】:2017-10-09 14:24:51
【问题描述】:

标记:

<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 w/o JQuery 的任何其他 li 上?

【问题讨论】:

  • 请在minimal reproducible example 中附上您尝试过的内容。您在这里拥有的是工单,而不是问题。
  • 您到底想达到什么目的?您的问题听起来像是您想将 .active 类随机移动到任何其他 li 元素上,但我猜这不是您真正想要的?
  • @JamesDonnelly,感谢您的回复!我的目标是从第一个 li 关闭 .active 并将其设置为最后一个 li 元素。

标签: javascript css-selectors


【解决方案1】:

试试这个:

// 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 中不起作用;
  • 我认为您必须根据需要修改添加类行。

【讨论】:

    【解决方案2】:

    你可以试试这样的:

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

      【讨论】:

        猜你喜欢
        • 2021-11-12
        • 2021-01-31
        • 2019-07-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-26
        相关资源
        最近更新 更多