How to hide new elements in jQuery?

I have this code:

var $msg = jQuery('<div></div>') .hide() .appendTo(document.body) ; if ($msg.is(":hidden")) { console.log("hidden"); } else { console.log("visible"); } 

On startup, it registers "hidden" in Firefox, but "visible" in Google Chrome. Is this a mistake, or am I doing something wrong?

+4
source share
2 answers

Did you try to hide after adding it to the body?

 $(function() { var $msg = jQuery('<div>hello</div>').appendTo(document.body).hide(); if ($msg.is(":hidden")) { console.log("hidden"); } else { console.log("visible"); } }); // $() 

worked for me in both browsers.

+4
source

as eed3si9n said the .hide() call was before the .appendTo() call.

I thought I would just add this answer as I found another way that also works:

 jQuery('<div></div>') .css("display", "none") .appendTo(document.body) ; 

I don’t know for sure whether this works, but I believe that adding an element to the DOM with it should be faster, since the browser does not need to display it?


An update for those of you that I like and need to know exactly how things work:

Code for jQuery.hide () - comments added by me

 hide: function(speed,callback){ return speed ? // this block of code won't be run, since speed will be undefined this.animate({ height: "hide", width: "hide", opacity: "hide" }, speed, callback) : // this is the relevant code this.filter(":visible").each(function(){ this.oldblock = this.oldblock || jQuery.css(this,"display"); // you can see here that it merely sets the display to 'none' this.style.display = "none"; }).end(); } 

and here is the code for the selector :hidden :

 hidden: function(a) { return "hidden" == a.type // <input type="hidden" /> || jQuery.css(a, "display") == "none" // style.display = none || jQuery.css(a, "visibility") == "hidden"; // style.visibility = hidden } 

This does not actually explain why Chrome does not show the element as hidden, though ...

0
source

All Articles