Use the negation selector ":not(:hidden)"
in .children()
:
$('.listagem-usuarios').children(":not(:hidden)").length
This will exclude elements with display: none
of the search (the display: none
is the result of the method .hide()
). In the example below, there is a hidden div:
$(".bt1").click(function(){
$('.listagem-usuarios').append('<div>abc <a href="javascript: void(0)" onclick="this.parentNode.remove()">Excluir</a></div>');
});
$(".bt2").click(function(){
console.clear();
if($('.listagem-usuarios').children(":not(:hidden)").length){
console.log('não tá vazio!');
}else{
console.log('está vazio!');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Clique em "Verificar" antes de adicionar elementos:
<br>
<button class="bt1">Adicionar elementos</button>
<div class="listagem-usuarios">
<div style="display: none;">div oculta</div>
</div>
<button class="bt2">Verificar</button>
Another way is to check by the contents of the div (.contents()
). For example, if there is a text node (a text without a container), the .children()
will not find and will inform that the div is empty, when in fact it is not.
For example:
<div class="listagem-usuarios">
<div style="display: none;">div oculta1</div>
<div style="display: none;">div oculta2</div>
abc <<< nó de texto não detectado pelo .children()
</div>
The .contents()
will return all internal nodes of the div in array form. Any text, element or line break is considered a node. Then picking up the content you can scroll through all nodes by checking what is visible and not empty (blanks):
$(".bt1").click(function(){
$('.listagem-usuarios').append('abc ');
});
$(".bt3").click(function(){
$('.listagem-usuarios').append('<div>uma div</div>');
});
$(".bt2").click(function(){
var achou;
var html = $('.listagem-usuarios').contents();
for(var item of html){
if(!$(item).is(":hidden") && $(item).text().trim().length){
achou = true;
break;
}
}
if(achou){
console.log('não tá vazio!');
}else{
console.log('está vazio!');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="bt1">Adicionar texto puro</button>
<button class="bt3">Adicionar um elemento</button>
<div class="listagem-usuarios">
<div style="display: none">div oculta</div>
</div>
<button class="bt2">Verificar</button>
It didn’t work... always falls on Else. I don’t know if it can be pq elements are inserted with append...
– user134546
Post your code of how your html looks when it is hidden please.
– Pedro Paulo
I’m sorry, I had read the question as if he wanted to take all the children of a div. I didn’t realize that I wanted to ignore the occult.
– Pedro Paulo