How to Select All Hidden Elements Using jQuery

Selecting hidden elements in jQuery is a straightforward task primarily accomplished using the :hidden pseudo-class selector. This article provides a quick guide on how to use this selector to target hidden HTML elements, explains how jQuery determines an element's visibility, and covers practical code examples for manipulating or revealing these elements in the Document Object Model (DOM).

The :hidden Selector Syntax

To select all hidden elements across the entire page, use the global :hidden selector:

$(":hidden");

To narrow the search to a specific tag or container for better performance, prepend the element selector:

// Selects all hidden <div> elements
$("div:hidden");

// Selects all hidden elements inside a specific container
$("#myContainer :hidden");

What jQuery Considers "Hidden"

jQuery checks an element's physical layout to decide if it is hidden. The :hidden selector matches an element if:

  • It has a CSS display value of none.
  • It is a form element with type="hidden".
  • Its width and height are explicitly set to 0.
  • Any of its ancestor elements are hidden, removing it from the document layout.

Important Caveat: Visibility and Opacity

The :hidden selector does not select elements styled with visibility: hidden or opacity: 0. These properties keep the element in the document's layout flow even though it is invisible to the human eye.

If you need to select elements that are hidden using visibility: hidden, use the .filter() method instead:

var invisibleElements = $("*").filter(function() {
    return $(this).css("visibility") === "hidden";
});

Practical Examples

1. Showing All Hidden Elements

To find all hidden elements of a specific type and make them visible:

$("p:hidden").show();

2. Counting Hidden Elements

To count how many elements are currently hidden inside a form or section:

var hiddenCount = $("#surveyForm :hidden").length;
console.log("Hidden elements found: " + hiddenCount);

3. Iterating Over Hidden Elements

To perform an action on each hidden element individually:

$("input:hidden").each(function() {
    console.log("Hidden input name: " + $(this).attr("name"));
});