rmondesilva rmondesilva - 7 months ago 17
Javascript Question

Count number of first layer/set of children in cloned element

I am trying to count the number of it's first layer of children not including it's child of child of child.. This is my codes

HTML

<div class="container">
<div class="row">
<div class="btn-container col-md-12">
<a href="#">Hello</a>
</div>
</div>
</div>


JS

$('a').click(function(){
var c = $(this).closest('.row').clone();
$(this).after( c );
var count = $(this).closest('.row').find('.btn-container').length;
alert(count);
});


The alert should always return 1 since the cloned element is appended inside of it.

enter image description here

jsFiddle

I tried ..

.find()
but also as I expected, it will count all inside of it.. Child of child of child and so on...

var parent = $(this).closest('.row');
var count = $('.btn-container', parent).length;


But still can not get what I want.

I already think of adding a name/class specifying to them. Like
btn-container first-children
..

But I am wondering if there is a jQuery trick that will make it simplier.

Answer

Rather than find() you could use children(). From jQuery .children() documentation:

The .children() method differs from .find() in that .children() only travels a single level down the DOM tree while .find() can traverse down multiple levels to select descendant elements (grandchildren, etc.) as well

var count = $(this).closest('.row').children('element-selector').length;
Comments