Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Remove specific style tags

Tags:

jquery

css

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

like image 855
neil Avatar asked Sep 11 '25 04:09

neil


1 Answers

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>
like image 94
T.J. Crowder Avatar answered Sep 12 '25 20:09

T.J. Crowder