如何在javascript中移除标签子类的类别

如何在javascript中移除标签子类的类别

问题描述:

如何移除活动类。下面是我的代码,第一个我觉得ID标签,则class但是这个代码不工作:如何在javascript中移除标签子类的类别

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>

+1

使用jquery它只有两行代码// ex $(“element1”)。removeClass(“active”); –

+0

我已更新我的代码 –

+0

给你的代码 –

试试这个片断

function myFunction() { 
 
    var fig = document.querySelectorAll('figure'); 
 

 
    for (var i = 0; i < fig.length; i++) { 
 
    if (fig[i].className == "active") { 
 
     fig[i].className = ""; 
 
    } 
 
    } 
 

 
}
.active { 
 
    color: purple; 
 
}
<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>

+0

伟大的工程我喜欢这个代码测试它与我的所有条件 –

+0

我还有一个问题,你怎么能得到当前的数字标签,它有活动类的孩子 –

+0

如果你只有一个子元素'fig [i] .children [0] .className' – cheralathan

如果我理解正确的话,你想删除第二<figure>的ID。您可以使用JS方法removeAttribute()。它使您能够从元素标签中删除任何属性。

var removeClass = function(selector) { 
 
    var el = document.querySelector(selector); 
 
    el.removeAttribute('id'); 
 
}
#active { 
 
    color: red; 
 
}
<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>

+0

你已经完全改变我的状况,因为我提到这是一个插件任何其他解决此问题与我的代码相同 –

+0

你需要工作一点,而不是要求更正代码。你想删除一个特定的元素或所有具有.active的元素吗? – Ivan

,你可以尝试使用classList.remove()图形元素上功能

function myFunction() { 
    var element1 = document.getElementById('grid3d'), 
     remove_class = 'active', 
     figureEl = element1.querySelector('.' + remove_class); 


    figureEl.className.remove(remove_class); 
} 

我希望它能起作用。

+0

对我不起作用 – Ivan

+0

我还有一个问题,我们如何才能获得当前具有活动类的数字标记的子节点 - –

+0

以类似的方式,如下所示: el.querySelector('figure.active'); // el可以是数字元素 –