我有以下内容:
<div id="elementor-tab-title-1141" class="elementor-tab-title elementor-active">
...some stuff...
</div>
我需要一个JavaScript代码来查找该类中的所有元素,并删除“ elementor-active”。因此,JavaScript在页面加载后运行后,代码应如下所示:
<div id="elementor-tab-title-1141" class="elementor-tab-title">
...some stuff...
</div>
这是我尝试过的:
function changeClass()
{
var classNameArray= document.getElementsByClassName("elementor-tab-title elementor-active");
for(var i = (classNameArray.length - 1); i >= 0; i--)
{
classNameArray[i].innerHTML =
getClassName(classNameArray[i].innerHTML);
classNameArray[i].className = "elementor-tab-title";
}
}
谢谢!
答案 0 :(得分:1)
您可以使用querySelectorAll()
定位所有元素,然后遍历它们以使用classList.remove()
从元素中删除类:
var elList = [].slice.call(document.querySelectorAll('.elementor-tab-title'));
elList.forEach(function(el){
el.classList.remove('elementor-active');
});
.elementor-tab-title{
color: green;
}
.elementor-active{
color: red;
}
<div id="elementor-tab-title-1141" class="elementor-tab-title elementor-active">
...some stuff...
</div>
<div id="elementor-tab-title-1142" class="elementor-tab-title elementor-active">
...some stuff2...
</div>
<div id="elementor-tab-title-1143" class="elementor-tab-title elementor-active">
...some stuff3...
</div>
答案 1 :(得分:1)
按照以下步骤
querySelectorAll()
获取带有该class
的所有元素forEach()
循环classList.remove()
删除该特定的类
[...document.querySelectorAll('elementor-tab-title,.elementor-active')].forEach(x => x.classList.remove('elementor-active'))
console.log(document.body.innerHTML)
<div id="elementor-tab-title-1141" class="elementor-tab-title elementor-active">
...some stuff...
</div>
使用jQuery
您可以使用jQuery removeClass()
$('.elementor-tab-title').removeClass('elementor-active');
console.log(document.body.innerHTML)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="elementor-tab-title-1141" class="elementor-tab-title elementor-active">
...some stuff...
</div>