Reputation: 2317
I am trying to do something if the div with the id "err_msg" is hidden. But the code below is returning true when the element is not hidden. Why is that happening?
<script>
$(function () {
var error_msg = $("#err_msg");
if(error_msg.filter(":hidden")){
console.log("The error message is hidden");
}
});
</script>
<body>
<div id="err_msg">Test </div>
Upvotes: 0
Views: 464
Reputation: 20636
Use is(':hidden')
,
error_msg.is(":hidden")
.filter() will always return an object. Empty or not, it will be true.
$(function () {
var error_msg = $("#err_msg");
if(error_msg.is(":hidden")){
console.log("The error message is hidden");
}
})
Upvotes: 2
Reputation: 413826
Any jQuery method like that will always return an object, and an object is never "falsy".
If you want to check if a jQuery object is empty, check .length
:
if (error_msg.filter(":hidden").length) {
console.log("it's hidden");
}
The library maintains .length
as if the object were an array, so if the length is zero then there's nothing in it; if it's non-zero then there's at least one element.
Upvotes: 3