删除空样式属性

时间:2016-12-14 04:34:46

标签: javascript jquery

是否可以仅删除空样式属性?

例如,如果我向元素添加动态填充:

$('div').css('padding', '10px');
<div style="padding:10px"></div>

然后我用jQuery删除它

$('div').css('padding', '');

看着萤火虫我最终

<div style=""></div>

我想要做的是仅在不包含任何内联样式时删除样式属性。

4 个答案:

答案 0 :(得分:1)

您可以使用检查样式值尝试此操作:

if ($("div").attr("style") === "")
  $("div").removeAttr("style");

希望这个答案能帮到你。

答案 1 :(得分:0)

您可以使用removeAttr方法:

&#13;
&#13;
if ($('div').attr('style') === '') {
  $('div').removeAttr('style')
}
&#13;
div:before {
  content: '<div> ';
}

div:after {
  content: ' </div>';
}

div:before,
div:after {
  font-style: Consolas;
  font-size: 13px;
  color: #7D2727;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div style="">no style attribute</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

有两种情况需要检查:当样式属性为no(undefined)或style属性为空时。我注意到jQuery方法removeAttr()removeProp()不起作用。我使用了DOM方法removeAttribute

$('p').each(function(i, e){
  
    var styleAttr = $(e).attr('style');

    if(!styleAttr || styleAttr == ''){
        
       e.removeAttribute('style'); // use DOM methods

    }
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p style="display:table;color:#ddd;">Test</p>
<p style="">Test</p>
<p>Test</p>

答案 3 :(得分:0)

试试这个:

document.querySelectorAll('[style=""]').forEach((el) => { 
   el.removeAttribute('style')
})

PS:将 document 改为任意选择器