A brief description of the selectors of jQuery
, when you set a selector to JQuery scans the DOM
and groups all the results of the respective query, in your code example you used the following query;
$(".pai .filha").length;
This query consists of the following: all elements with the child class that are inside an element with the parent class, summarizing considering how you structured your HTML all the divs with the child class fall into that rule so the result of the query would be 5 .
As sadly jQuery does not allow us to group the child nodes given to their parents in a simple way to solve their problem, a more appropriate approach would be to group parents, go through their parents and count the number of children.
But since everything in this life is not flowers, let's talk about the prototype $.data
which we use in the example below to set the value of the data-childs parameter,
Unfortunately this feature values the value however it does not force an update of the gift or this date will only be accessible via javascript and if you try to view the parameter by Firebug or Chrome Inspector, you will realize that HTML
remains the same and if you try to access by CSS
or similar it will not work either, so if you intend to use the date value for purposes other than just javascript, beware of replacing $.data
with $.attr
.
Below is a snippet attesting to the statements made above.
$('.pai').each(function(){
$(this).data('childs', $(this).children('.filha').size())
})
// Confirmando os valores do atributo data da primeira div, você deve remover na implementação.
alert($('.pai:eq(0)').data('childs'))
// Confirmando os valores do atributo data da segunda div, você deve remover na implementação.
alert($('.pai:eq(1)').data('childs'))
// Provando que o data-setado pelo jQuery não necessariamente atualiza o DOM
// Colocando o data da segunda div como parameter(atualiza o DOM) e o css reconhece o atributo.
$('.pai:eq(1)').attr('data-childs', $('.pai:eq(1)').data('childs'))
.pai { background: #ccc; padding: 20px; text-align: center; margin: 25px 0; }
.pai:after {
content: attr(data-childs); display: block; text-align: center; color: blue;
}
.filha { background: #fff; width: 50px; height: 50px; display: inline-block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="pai">
<div class="filha"></div>
<div class="filha"></div>
<div class="filha"></div>
</div>
<div class="pai">
<div class="filha"></div>
<div class="filha"></div>
</div>