jquery-attributes

jquery choosing methods


I love using the hide() and show() methods, but I've come across someone's scripting where they never use it.
Instead I see them using attr() for anything related to display.

$("#element").attr("style", "visibility:hidden");
$("#element").attr("style", "visibility:visible");

Is this just purely preferential?
Or is it more beneficial to use one vs the other?


Solution

  • There is a difference. Take .hide() for example:

    This is roughly equivalent to calling .css('display', 'none'), (...)

    visibility and display are two different CSS properties. Using visibility: hidden; leaves space for the element in the layout but does not display it.

    Another (minor) difference is that calling .attr("style", '...') will override all other styles that might be set on the element.