Tuesday, April 17, 2012

possible to remove inline styles with jquery?


a jquery plugin is applying an inline style (display:block), I'm feeling lazy and i want to override it with display:none,



what's the best (lazy) way?


Source: Tips4all

7 comments:

  1. I know this is an old question, but I was looking for an answer to this myself, and couldn't find an answer elsewhere.
    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.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.

    And finally, 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.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 jQuery will remove it for you.

    What a waste of time...

    ReplyDelete
  2. .removeAttr("style") to just get rid of the whole style tag...
    .attr("style") to test the value...
    .attr("style",newValue) to set it to something else

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

    $('something:visible').css('display', 'none');

    ReplyDelete
  4. 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.

    ReplyDelete
  5. $('div[style*=block]').removeAttr('style');

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

    ReplyDelete