How to set "style=display:none;" using jQuery's attr method?

user4407686 picture user4407686 · Jan 8, 2015 · Viewed 249k times · Source

Following is the form with id msform that I want to apply style="display:none" attribute to.

<form id="msform" style="display:none;">
</form>

Also the check should be performed before adding the "style=display:none;" property. That is if it is already set like in above code it should not set again.

But if it's not set then it should.

How should I achieve this? Please help me.

Answer

Gone Coding picture Gone Coding · Jan 8, 2015

Why not just use $('#msform').hide()? Behind the scene jQuery's hide and show just set display: none or display: block.

hide() will not change the style if already hidden.

based on the comment below, you are removing all style with removeAttr("style"), in which case call hide() immediately after that.

e.g.

$("#msform").removeAttr("style").hide();

The reverse of this is of course show() as in

$("#msform").show();

Or, more interestingly, toggle(), which effective flips between hide() and show() based on the current state.