3

I have set up 4 divs to test the different results of using:

$("#div1").hide();
$("#div2").prop("hidden", true);
$("#div3").css("display","none");
$("#div4").attr("hidden", true);

I can see that the result is (I am using version 1.11.3):

<div id="div1" style="display: none;">Something</div>
<div id="div2" hidden="">Something</div>
<div id="div3" style="display: none;">Something</div>
<div id="div4" hidden="hidden">Something</div>

It seems kind of confusing to me to have four different ways of achieving pretty much the same result. I have seen some explanation in .hide() or display: none? jQuery but I wonder if someone can provide more information and mainly, when should I use which??

2
  • hidden is kind of new, and its attr maps to the prop, just like say, "title", so thats why "both" prop+attr look the same... .hide() is a shortcut. really though, i think the best way is to use classes, in bootstrap .hidden works. Commented Nov 6, 2015 at 20:35
  • Did you not read the first answer? It's right there. "This is roughly equivalent to calling .css('display', 'none')" Commented Nov 6, 2015 at 20:35

2 Answers 2

3
//this is a wrapper function.  simply adds display none inline.  for ease of use
$("#div1").hide();
//prop is used to manipulate any property on the object.  hidden is a property.  so it doesn't stop you from doing it.
$("#div2").prop("hidden", true);
//css is a wrapper for the style attribute.  display is a valid css property so it won't stop it
$("#div3").css("display","none");
//this one seems odd.  i thought it would be hidden="hidden"  but anyway.  attr() is used to change the attributes on the markup.  hidden is a valid attribute so it doesn't stop you
$("#div4").attr("hidden", true);

It's all about your style of coding. If they all work, you get to use the one that you like best. Just try to be consistent if possible, imho.

Sign up to request clarification or add additional context in comments.

Comments

0

There sure is a difference, but I'm not going to cover them all.

A real life story:

I just had a project, in which I needed to filter DOM elements by their display property. Same DOM elements was set to 'none', by using .hide() and shown by setting .show()

This usage, while short and neat, made problems filtering by display property, as it always showed 'none' in a console output. Even if the element list showed 'block'. So a caching occours using .hide()

You don't just wanna use whatever you like best. Only if you like best what works for your specific needs ;)

1 Comment

Welcome to SO. This post doesn't address the technical issue raised in the question. See stackoverflow.com/help/how-to-answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.