如何删除活动课程。下面是我的代码,首先我找到id标签然后是类,但是这段代码不起作用:
function myFunction() {
var element1 = document.getElementById('grid3d');
var remove_class = 'active';
element1.className = element1.className.replace(' ' + remove_class, '').replace(remove_class, '');
}

.active {
color: red;
}

<div id="grid3d">Hello World
<figure ">Click the button to remove the class attribute from the h1 element.</figure>
<figure class="active ">Click the button to remove the class attribute from the h1 element.</figure>
<figure>Click the button to remove the class attribute from the h1 element.</figure>
</div>
<button onclick="myFunction() ">Try it</button>
&#13;
答案 0 :(得分:3)
试试这个代码段
function myFunction() {
var fig = document.querySelectorAll('figure');
for (var i = 0; i < fig.length; i++) {
if (fig[i].className == "active") {
fig[i].className = "";
}
}
}
&#13;
.active {
color: purple;
}
&#13;
<div id="grid3d">Hello World
<figure>Click the button to remove the class attribute from the h1 element.</figure>
<figure class="active">Click the button to remove the class attribute from the h1 element.</figure>
<figure>Click the button to remove the class attribute from the h1 element.</figure>
</div>
<button onclick="myFunction()">Try it</button>
&#13;
答案 1 :(得分:1)
你可以尝试在图元素
上使用classList.remove()函数function myFunction() {
var element1 = document.getElementById('grid3d'),
remove_class = 'active',
figureEl = element1.querySelector('.' + remove_class);
figureEl.className.remove(remove_class);
}
我希望它能奏效。
答案 2 :(得分:0)
如果我理解正确,您想删除第二个<figure>
的ID。您可以使用JS方法removeAttribute()
。它使您可以从元素标记中删除任何属性。
var removeClass = function(selector) {
var el = document.querySelector(selector);
el.removeAttribute('id');
}
&#13;
#active {
color: red;
}
&#13;
<div>Remove #active! from the second figure tag
<figure>Click the button to remove the class attribute from the h1 element.</figure>
<figure id="active">Click the button to remove the class attribute from the h1 element.</figure>
<figure>Click the button to remove the class attribute from the h1 element.</figure>
</div>
<button onclick="removeClass('#active')">Try it</button>
&#13;