JavaScript 移除div下p标签 style

星陨丶作者头像
星陨丶 2025-05-08

在JavaScript中,移除<div>下的所有<p>标签的样式。


1、使用element.style.removeProperty()

如果你知道要移除的具体CSS属性,可以直接使用removeProperty()方法。

例如,移除所有<p>标签的color属性:

<script>
    // 获取所有的p标签
    var ps = document.querySelectorAll('div p');
    //也可以这样写 若 div 的 id =  div-id-name
    //var ps = document.querySelectorAll('#div-id-name p');
    
    // 遍历所有p标签并移除color属性
    ps.forEach(function(p) {
        p.style.removeProperty('color');
    });
</script>

2、使用element.removeAttribute()

如果你想移除style属性本身(这将移除所有内联样式),可以使用removeAttribute()方法:

<script>
    // 获取所有的p标签
    var ps = document.querySelectorAll('div p');
    //也可以这样写 若 div 的 id =  div-id-name
    //var ps = document.querySelectorAll('#div-id-name p');
    
    // 遍历所有p标签并移除style属性
    ps.forEach(function(p) {
        p.removeAttribute('style');
    });
</script>