如果有这个类的元素,如何在体内找到

时间:2015-12-02 13:27:47

标签: javascript html

我在纯JavaScript中编写代码,如何在aul>li>a)上找到是否有任何class ='active'。

<ul class="tabs">
    <li class="tabs-content"><a href="#" onclick="activatetb(this)" class="item-0">Item0</a></li>
    <li class="tabs-content"><a href="#" onclick="activatetb(this)" class="item-1">Item1</a></li>
    <li class="tabs-content"><a href="#" onclick="activatetb(this)" class="item-2">Item2</a></li>
    <li class="tabs-content"><a href="#" onclick="activatetb(this)" class="item-3">Item3</a></li>
</ul>

my js

document.getElementsByClassName('active')

1 个答案:

答案 0 :(得分:3)

修改

&#13;
&#13;
var elements = document.getElementsByClassName("tabs")[0].getElementsByClassName("active") // like this
var elements = document.querySelectorAll('ul li a.active') // or like this @Jhuliano Moreno 
for (let i = 0; i < elements.length; ++i) {
  elements[i].classList.remove("active")
}

// Inefficiant on-liner:
Array.prototype.slice.call(document.querySelectorAll('ul li a.active'),0).forEach(function(el){el.classList.remove("active")})
&#13;
.active {
    color: red;
}
&#13;
<ul class="tabs">
  <li class="tabs-content"><a href="#" onclick="activatetb(this)" class="item-0">Item0</a></li>
  <li class="tabs-content"><a href="#" onclick="activatetb(this)" class="item-1">Item1</a></li>
  <li class="tabs-content"><a href="#" onclick="activatetb(this)" class="item-2">Item2</a></li>
  <li class="tabs-content"><a href="#" onclick="activatetb(this)" class="item-3 active">Item3</a></li>
</ul>
&#13;
&#13;
&#13;

<强> OLD:

&#13;
&#13;
if (document.getElementsByClassName('active').length > 0) {
    // Yes there are
  } else {
    // No there are not
  }
&#13;
<ul class="tabs">
  <li class="tabs-content"><a href="#" onclick="activatetb(this)" class="item-0">Item0</a></li>
  <li class="tabs-content"><a href="#" onclick="activatetb(this)" class="item-1">Item1</a></li>
  <li class="tabs-content"><a href="#" onclick="activatetb(this)" class="item-2">Item2</a></li>
  <li class="tabs-content"><a href="#" onclick="activatetb(this)" class="item-3 active">Item3</a></li>
</ul>
&#13;
&#13;
&#13;