0

It seems like elements that are not in the DOM are considered to be hidden, regardless of the CSS applied to those elements

for instance, putting the following in the Chrome console evaluates to false:

$('<div style="display: block;">i am a div</div>').is(":visible")

Is there any way to check if a detached element like the one above is visible or not. I don't just want to check that display css property is block.

1
  • shoudl be - $('<div style="display: block;">i am a div</div>').find('div').is(":visible")
    – i--
    Commented Mar 7, 2013 at 21:01

4 Answers 4

1

It depends on what you are trying to do, but the simplest thing would be to attach it to check:

var $div = $("<div>");
$div.appendTo("body").is(":visible");
$div.detach();

If this check is prohibitive for you, you can check both the display and visibility CSS to check that they are not none and hidden, respectively, and that the hidden attribute is not set. You could also do something like set position: fixed; top: 100% and do the above test.

EDIT: seems like jQuery's hidden check is:

jQuery.css( elem, "display" ) === "none"
|| !jQuery.contains( elem.ownerDocument, elem )

So you could just get rid of the second line there to do an equivalent check.

1

Sure you can

var foo = $('<div style="display: block;">i am a div</div>');
foo.appendTo('body');

var vis = foo.is(":visible");

console.log(vis);

foo.detach();

Not sure why you'd ever want to try this, though.

0

Try this:

$('<div style="display: block;">i am a div</div>').css("display")!="none"
0

If an element is not attached to a DOM then browser does not treat it as visible, because simply put it does not have a parent which might affect it's visibility also

Not the answer you're looking for? Browse other questions tagged or ask your own question.