Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between using hide, prop, attr or css to hide an element with JQuery

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??

like image 217
Rodrigo Avatar asked Feb 21 '26 18:02

Rodrigo


1 Answers

//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.

like image 157
Taplar Avatar answered Feb 24 '26 09:02

Taplar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!