A brief description of the selectors jQuery
, when you define a selector 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 as follows: all elements with the daughter class that are within an element with the parent class, summarizing considering the way you structured your HTML all Divs with the daughter class fall into this rule so the result of the query would be 5.
As unfortunately 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 the parent poles, go through the respective ones and count the number of children.
But since not everything in this life is 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 arrow the value however it does not force a gift update ie that date will only be accessible via javascript and if you try to view the parameter by Firebug or Inspector of Chrome, you will realize that the HTML
remains the same and if you try to access by CSS
or similar will not work either, so if you intend to use the date value for purposes other than javascript only, beware of replacing the resource $.data
for $.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>
<div class="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>
Gabriel, the
$(this).data('childs', value)
does not update thedata-childs
, you must use thethis.dataset.childs = value
or$(this).attr('data-childs', value)
.– Tobias Mesquita