Reputation: 1306
Our form software generates lots of inline style
attributes, which I'd like to remove. I know this can be done fairly swiftly with something like $('div[style]').removeAttr('style')
but unfortunately, I need to keep all display:none
as these can be shown later, depending on conditional choices.
Based on https://stackoverflow.com/questions/2465158/is-it-possible-to-remove-inline-styles-with-jquery, I know something like $('div').css('color', '');
would work but I would need to repeat for font-size
, text-align
, etc.
So, what would be a more efficient way (with jQuery, preferably) to remove all style tags that are not display
, preferably in a chaining/one-line statement? I thought about using :not
but can't figure out how to combine with the above example...
Thanks
Upvotes: 4
Views: 1627
Reputation: 1074335
You can remove all style
attributes but keep any existing display: none
flags by using the selector you showed, then detecting the display: none
and reasserting it after removing the style:
$("div[style]").each(function() {
var hide = this.style.display === "none";
$(this).removeAttr("style");
if (hide) {
this.style.display = "none";
}
});
Or more generally, keeping the display
property regardless of its value:
$("div[style]").each(function() {
var display = this.style.display;
$(this).removeAttr("style");
this.style.display = display;
});
Complete example: Fiddle
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<meta charset=utf-8 />
<title>Style Update</title>
</head>
<body>
<div>No style</div>
<div style="color: green">Green</div>
<div style="color: red; display: none">Red, hidden</div>
<div><button type="button" id="processStyle">Process style attributes</button></div>
<div><button type="button" id="showHidden">Show hidden briefly</button></div>
<p>Click "Show hidden briefly" first, then "Process style attribuets", then "Show hidden briefly" again.</p>
<script>
$("#processStyle").click(function() {
$("div[style]").each(function() {
var display = this.style.display;
$(this).removeAttr("style");
this.style.display = display;
});
});
$("#showHidden").click(function() {
$("div").each(function() {
if (this.style.display === "none") {
$(this).fadeIn('fast').delay(1000).fadeOut('fast');
}
});
});
</script>
</body>
</html>
Upvotes: 5
Reputation: 1463
none = false;
if($(selector).css('display')=='none')
none = true;
$(selector).removeAttr('style');
if(none)
$(selector).css('display','none');
Upvotes: 0
Reputation: 82241
what you can do is store the style(or styles) you want, remove them all and then set stored style again. Something like this:
$('.selector').each(function() {
var keepStyle, $el;
$el = $(this);
keepStyle = {
display: $el.css('display')//use comma seprated css style for multiple style
};
$el.removeAttr('style')
.css(keepStyle);
})
Upvotes: 2