Is it possible to toggle the visibility of an element, using the functions .hide(), .show() or .toggle()?

How would you test if an element is visible or hidden?

javascript jquery dom visibility 

Nov 17

2 Answers

Since the question refers to a single element, this code might be more suitable:

You can use the hidden selector:

// Matches all elements that are hidden
$('element:hidden')

You can use the visible selector:

// Matches all elements that are visible
$('element:visible')

Or you can simplify the same with is as follows.

$(element).is(":visible")

answered Dec 20


Check if Element is Hidden with .css("visibility")

Let's add two more items into our DOM:

<p class="second-element">This is the second paragraph.</p>
<p class="third-element">This is the third paragraph.</p>

Refresh/reload your page and confirm that new elements are added.

Now we will change the visibility property of the second-element. To do so, you can create a CSS file and link it to your HTML file or write your CSS code inside the <head> tag of your HTML file, inside the <style></style> tags:

.second-element{
    visibility: hidden; 
}

Now this part is a bit tricky. Before reloading the page, take a good look at the current position of the third-element. If you refresh the page, you will notice that the second-element is not visible anymore, but it still takes up the same space. It is not visible, yet the position of the third-element implies that it's still there. In fact, if we go ahead and run our previous functions for this element:

var myElement = ".second-element";
console.log(myElement + " is hidden?: " + $(myElement).is(":hidden"));
console.log(myElement + " is visible?: " + $(myElement).is(":visible"));

We would get the result that it is not hidden, but it still is visible:

.second-element is hidden?: false
.second-element is visible?: true

The reason is that when you set the visibility property to hidden, it becomes invisible but it is still rendered by the browser, so it takes up its initial space. Most browsers consider elements visible if it has height and/or width. In other words, any element with zero dimensions is considered hidden.

Now that we know what we're dealing with, all we have to do is to check if visibility property of the element is set to hidden, not whether the element itself is hidden:

var myElement = ".second-element";
console.log(myElement + " is visibility === hidden?: " + ($(myElement).css("visibility") === "hidden"));

This will return true:

.second-element is visibility === hidden?: true

While we're at it, let's work out what other CSS properties affect the visibility.

answered Dec 30


Login and Submit Your Answer
Browse other questions tagged  javascript  jquery  dom  visibility or ask your own question.