Alko
Alko

Reputation: 1439

Remove an empty style attribute

Is it possible to remove only empty style attribute?

For example if I add dynamically padding to an element:

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

Then I remove it with jQuery like

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

Looking at the firebug I end up with

<div style=""></div>

What I would like to do is remove style attribute only if does not contain any inline style.

Upvotes: 0

Views: 2079

Answers (4)

l2aelba
l2aelba

Reputation: 22167

Try this:

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

PS: Change document to any selector

Upvotes: 0

Adam Azad
Adam Azad

Reputation: 11297

There are two cases to check for: when the style attribute is no there (undefined) or the style property is empty. I noticed jQuery methods removeAttr(), removeProp() did not work. I used DOM method 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>

Upvotes: 0

Hitesh-Systematix
Hitesh-Systematix

Reputation: 100

You can try this with check style value:

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

Hope this answer will help you.

Upvotes: 2

GG.
GG.

Reputation: 21844

You can use the removeAttr method:

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

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

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

<div style="">no style attribute</div>

Upvotes: 0

Related Questions