Reputation: 1597
I want to show a div which has the error message span visible in it. I tried the following codes but it works only when the container is visible otherwise it is unable to find in it.
Can someone share the reason and solution to it?
Using .length
$(".has-warning:visible").each(function() {
var id = this.id;
var divs = ["wReq_div", "mcatIsq_div", "glDetail_div"];
for (var i = 0; i < divs.length; i++) {
if ($("#" + divs[i] + " #" + id).length) {
console.log("found in " + divs[i]);
return false;
}
}
});
This gives true for the container if it's visible otherwise not.
Using $.contains
$(".has-warning:visible").each(function(){
var id = this.id;
var divs = ["wReq_div","mcatIsq_div","glDetail_div"];
for(var i=0;i<divs.length;i++){
if($.contains($("#"+divs[i])[0],$("#"+id)[0])){
console.log("found in " + divs[i]);
return false;
}
}
});
It's also working only if the container is visible.
So my main problem is:
display
not none
, how to find that shown child in the hidden parentHere is the CodePen
I don't want to use the method of changing class from a hidden one to visible one to display my errorMsg as I'll have to do a lot of changes in multiple files.
Upvotes: 1
Views: 255
Reputation: 409
you will not find .has-warning:visible
as its parent is not visible. But you can check for parent div if it is hidden or not.
$(".has-warning").each(function() {
if($(this).css("display") != "none"){
var id = this.id;
var i=0;
var divs = ["wReq_div:hidden", "mcatIsq_div:hidden", "glDetail_div:hidden"];
for (i = 0; i < divs.length; i++) {
if ($("#" + divs[i] + " #" + id).length) {
alert("found in " + divs[i] + " " + id);
// Add code to display that div
}
else {
alert("not found in " + divs[i]+ " " + id);
}
}
}
});
Upvotes: 0
Reputation: 1597
I used following code to overcome this problem, Please suggest if you have better one:
var divs = ["wReq_div","mcatIsq_div","glDetail_div"];
$(".has-warning").each(function(){
if($(this).css("display") != "none"){
var id = this.id;
for(var i=0;i<divs.length;i++){
if($.contains($("#"+divs[i])[0],$("#"+id)[0])){
console.log("found in " + divs[i]);
break;
}
}
}
});
But it first selects all the divs and may increase time.
Upvotes: 1
Reputation: 2505
From the docs
jQuery( ":visible" )
Elements are considered visible if they consume space in the document. Visible elements have a width or height that is greater than zero.
If a parent is hidden, all it's children will also be hidden. So, $(".has-warning:visible")
will not return the child elements, even if they're not
hidden.
you need to rely on the display property of the child elements, rather than the :visible attribute and try something like this,
function checkMsg1(){
$(".has-warning").each(function() {
var id = this.id;
var i=0;
var divs = ["wReq_div", "mcatIsq_div", "glDetail_div"];
for (i = 0; i < divs.length; i++) {
if ($("#" + divs[i] +" #"+id).css("display") !== 'none') {
$("#" + divs[i]).show();
}
}
});
}
Upvotes: 2