我在纯JavaScript中编写代码,如何在a
(ul>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')
答案 0 :(得分:3)
修改强>
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;
<强> OLD:强>
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;