Find all hidden elements using jQuery
In this guide i will show you an easy way of finding
all hidden objects in an html document, using only one selector in jQuery
Our goal will be to find the 4 objects bellow (All hidden
using CSS, jQuery
or type=”hidden”)
<div style="display:none;">1</div>
<div id="jHide">4</div>
<div id="jFadeOut">5</div>
<input type="hidden" value="Hidden input field" />
The code above should
explain it self (; But as you can see, then we have 4 divs! One hidden with
“display: none”, two hidden with jQuery and finally one type=”hidden”
textfield. All of these have one thing in common, they are all hidden.
jQuery can find all
“Hidden” elements, but not elements with opacity at 0%. Because, technically
they still exists.
jHide =
$(“element”).hide();
jFadeOut = $(“element”).fadeout();
Below is the code that we will use to locate these
objects (Remember to link to the jQuery library)
<script src="jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#jHide").hide();
$("#jFadeOut").toggle();
//Get all hidden divs
var allHidden = $("body").find(":hidden");
var amount = allHidden.length;
alert("There is " + amount + " hidden elements on this page!");
});
</script>
At line 1 we link to our jQuery library (Your path “src” might be different).
At line4 we start our document.ready() function to
prevent this script from running before our DOM is fully loaded!
Line 4 and 5 is just for hiding two of our div’s. (:
At line 9 we use the magic!
$(“body”).find(“:hidden”);
That is
the exact code that jQuery provides us with to find all hidden objects in our
DOM. Our $(“body”)
is just to define that we will look inside our <body> tag
At line 12 we write the amount of matched elements out
using the alert() function.
That was
it! :D
Remember
to tell me what you think of this tutorial, in a comment ;)