251

A jQuery plugin is applying an inline style (display:block). I'm feeling lazy and want to override it with display:none.

What's the best (lazy) way?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Haroldo
  • 36,607
  • 46
  • 127
  • 169

15 Answers15

402

Update: while the following solution works, there's a much easier method. See below.


Here's what I came up with, and I hope this comes in handy - to you or anybody else:

$('#element').attr('style', function(i, style)
{
    return style && style.replace(/display[^;]+;?/g, '');
});

This will remove that inline style.

I'm not sure this is what you wanted. You wanted to override it, which, as pointed out already, is easily done by $('#element').css('display', 'inline').

What I was looking for was a solution to REMOVE the inline style completely. I need this for a plugin I'm writing where I have to temporarily set some inline CSS values, but want to later remove them; I want the stylesheet to take back control. I could do it by storing all of its original values and then putting them back inline, but this solution feels much cleaner to me.


Here it is in plugin format:

(function($)
{
    $.fn.removeStyle = function(style)
    {
        var search = new RegExp(style + '[^;]+;?', 'g');

        return this.each(function()
        {
            $(this).attr('style', function(i, style)
            {
                return style && style.replace(search, '');
            });
        });
    };
}(jQuery));

If you include this plugin in the page before your script, you can then just call

$('#element').removeStyle('display');

and that should do the trick.


Update: I now realized that all this is futile. You can simply set it to blank:

$('#element').css('display', '');

and it'll automatically be removed for you.

Here's a quote from the docs:

Setting the value of a style property to an empty string — e.g. $('#mydiv').css('color', '') — removes that property from an element if it has already been directly applied, whether in the HTML style attribute, through jQuery's .css() method, or through direct DOM manipulation of the style property. It does not, however, remove a style that has been applied with a CSS rule in a stylesheet or <style> element.

I don't think jQuery is doing any magic here; it seems the style object does this natively.

Joseph Silber
  • 214,931
  • 59
  • 362
  • 292
  • 3
    @ximi - Thanks man. I've been thinking about this, and I decided that this wasn't such a waste of time. It could be adopted to check for inline styles, for which there's currently no support for in jQuery (`.css('property')` gives you the value, but it doesn't tell you whether it came from an inline style). – Joseph Silber Oct 27 '11 at 21:08
  • I came to the same conclusion independently - empty string seems to do just what we want. It's not officially documented in the API, but hopefully will continue to work. – jrz Feb 12 '13 at 13:55
  • @Jonz - It *is* officially documented (though I don't know when it was added; I don't remember seeing it there when I originally posted this). Also, I don't think jQuery is the doing anything here. The native `style` object seems to behave in the same manner. I amended my answer with this information. – Joseph Silber Feb 12 '13 at 17:39
  • Does this work with things like font-family, or does the - mess up the regex? – TMH Jul 16 '14 at 15:38
  • @TomHart - The `-` does not mess up anything (couldn't you have just tried it?). Anyhow, you can stick to using `$el.css('font-family', '')` which does the same thing as my regex solution. – Joseph Silber Jul 16 '14 at 20:42
  • I created a jquery plugin based on this answer. https://github.com/moshfeu/jquery.removeStyle-plugin – Mosh Feu Feb 11 '15 at 14:13
  • 4
    @mosh - Why don't you just use `$('#element').css('display', '')`? – Joseph Silber Feb 11 '15 at 20:41
  • It's more "clean" I think. – Mosh Feu Feb 12 '15 at 08:03
  • I get an error if the style is undefined, i suggest to add if(typeof(style)!=="undefined") before return style.replace(search, ''); – Hamboy75 Oct 18 '17 at 13:14
  • $('#element').css('width', ''); FTW – Joe Johnston Dec 13 '18 at 21:38
176

.removeAttr("style") to just get rid of the whole style tag...

.attr("style") to test the value and see if an inline style exists...

.attr("style",newValue) to set it to something else

aug
  • 11,138
  • 9
  • 72
  • 93
heisenberg
  • 9,665
  • 1
  • 30
  • 38
  • 18
    This will affect _all_ inline styles, not just `display`. – SLaks Mar 17 '10 at 19:21
  • 1
    sounds good ill give it a try and let you know, i never use inline styles normally so happy to clear all inline styles – Haroldo Mar 17 '10 at 19:43
  • 12
    @Slaks well, that's what I meant by "get rid of the whole style tag" ;) – heisenberg Jan 23 '12 at 03:30
  • Hi. is there a way to check if some 'style' had been apply to the ... $('*') , from any source like an inlined style, styling atribute like font,b,strong, css file .. before atempting to remove / reset anything or just plain reset all one shot ? – Milche Patern Jan 28 '14 at 00:17
  • Since removing every inline style individually doesn't remove the (now-empty) `style` attribute, this is still worthy of note. – Brilliand Aug 05 '14 at 21:36
28

The easiest way to remove inline styles (generated by jQuery) would be:

$(this).attr("style", "");

The inline code should disappear and your object should adapt the style predefined in your CSS files.

Worked for me!

andr
  • 15,970
  • 10
  • 45
  • 59
15

you can create a jquery plugin like this :

jQuery.fn.removeInlineCss = function (properties) {
  if (properties == null) return this.removeAttr('style')
  properties = properties.split(/\s+/)
  return this.each(function () {
    for (var i = 0; i < properties.length; i++)
      this.style.removeProperty(properties[i])
  })
}

usage

$(".foo").removeInlineCss(); //remove all inline styles
$(".foo").removeInlineCss("display"); //remove one inline style
$(".foo").removeInlineCss("color font-size font-weight"); //remove several inline styles
Yukulélé
  • 15,644
  • 10
  • 70
  • 94
  • 2
    This answer contains a very neat one-line trick that's useful even without jQuery and which not many devs may know—calling `elem.style.removeProperty('margin-left')` will remove just `margin-left` from the `style` attribute (and return that property's value). For IE6-8 it's `elem.style.removeAttribute()`. – craigpatik Feb 24 '16 at 16:51
13

You can set the style using jQuery's css method:

$('something:visible').css('display', 'none');
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • @Kobi: He's asking about any inline style. – SLaks Mar 17 '10 at 19:26
  • err, what? I probably don't understand something. I'm thinking about `
    `, `$('div').hide()` .
    – Kobi Mar 17 '10 at 19:29
  • 3
    @Kobi: `hide` addresses one special case of modifying inline styles. This answer addresses all cases. (`hide/show` also have a limitation as two which two values are toggled. i.e. none->block or none->inline.) – Joel Mar 17 '10 at 19:32
  • @Joel: `hide` / `show` will remember the old value of `display` and restore it correctly. – SLaks Mar 17 '10 at 19:33
  • @SLaks: Cool. That must have been added recently, as I remember having trouble with it before. – Joel Mar 17 '10 at 19:41
  • @Joel: http://api.jquery.com/hide/: The matched elements will be hidden immediately, with no animation. This is roughly equivalent to calling .css('display', 'none'), except that the value of the display property is saved in jQuery's data cache so that display can later be restored to its initial value. If an element has a display value of inline, then is hidden and shown, it will once again be displayed inline. – SLaks Mar 17 '10 at 19:54
9

The Lazy way (which will cause future designers to curse your name and murder you in your sleep):

#myelement 
{
    display: none !important;
}

Disclaimer: I do not advocate this approach, but it certainly is the lazy way.

Joel
  • 19,175
  • 2
  • 63
  • 83
  • 2
    This is clearly the best answer to the question because its in the spirit of the bad practice "lazy". Cheers! – ktamlyn Jan 31 '13 at 15:25
6
$("[style*=block]").hide();
David Morton
  • 16,338
  • 3
  • 63
  • 73
6
$('div[style*=block]').removeAttr('style');
antpaw
  • 15,444
  • 11
  • 59
  • 88
6

If you want to remove a property within a style attribute – not just set it to something else – you make use of the removeProperty() method:

document.getElementById('element').style.removeProperty('display');

UPDATE:
I've made an interactive fiddle to play around with the different methods and their results. Apparently, there isn't much of a difference between set to empty string, set to faux value and removeProperty(). They all result in the same fallback – which is either a pre-given CSS rule or the browser's default value.

WoodrowShigeru
  • 1,418
  • 1
  • 18
  • 25
5

In case the display is the only parameter from your style, you can run this command in order to remove all style:

$('#element').attr('style','');

Means that if your element looked like this before:

<input id="element" style="display: block;">

Now your element will look like this:

<input id="element" style="">
paulalexandru
  • 9,218
  • 7
  • 66
  • 94
3

Here is an inlineStyle selector filter I wrote that plugs into jQuery.

$("div:inlineStyle(display:block)") // will select all divs with an inline style of display: block set

In your case you could use this like:

$("div:inlineStyle(display:block)").hide();
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Corban Brook
  • 21,270
  • 4
  • 28
  • 34
3

$el.css({ height : '', 'margin-top' : '' });

etc...

Just leave the 2nd param blank!

He Nrik
  • 1,670
  • 16
  • 17
Bert
  • 75
  • 1
  • 1
    If you guys down-vote something, please leave a comment. – He Nrik Dec 09 '14 at 11:07
  • 1
    I would guess you got the downvotes because you did not answer *the question asked*: `"jQuery plugin is applying an inline style (display:block). I'm feeling lazy and want to override it with display:none"`. Although your text is correct, your code does not solve the question. – iCollect.it Ltd May 15 '15 at 16:42
  • Solved the problem I had. Tnx. – yodalr Sep 05 '17 at 09:33
2

Change the plugin to no longer apply the style. That would be much better than removing the style there-after.

Josh Stodola
  • 81,538
  • 47
  • 180
  • 227
  • 1
    hence the 'lazy'! cant be arsed to find which bit of which plugin it is! – Haroldo Mar 17 '10 at 19:43
  • 4
    I don't know how you define lazy, I just answered how I would do it. Seems to make sense to fix the problem where it originates as opposed to patching things up outside of the plugin. I foresee messinesss when doing it that way. – Josh Stodola Mar 17 '10 at 19:55
  • Which way? If you edit plugin you may get problems after updating to new version which will override your change and mess up the layout. Who will remember in a year or so time that you made that one little adjustment there? I always try to find other solution than modifying plugin source code – Zefiryn Jun 05 '12 at 19:52
1

I had similar issue with width property. I couldnt remove the !important from code, and since it needed this style on a new template I added an Id (modalstyling) to the element and afterwards i added following code to the template:

<script type="text/javascript">
    $('#modalstyling').css('width', '');    //Removal of width !important
    $('#modalstyling').width('75%');        //Set custom width
</script>
Mbotet
  • 170
  • 2
  • 17
0

$("#element").css({ display: "none" });

At first I tried to remove inline style in css, but it does not work and new style like display: none will be overwritten. But in JQuery it works like this.

Cocoa3338
  • 95
  • 1
  • 2
  • 12