rmondesilva rmondesilva - 2 years ago 95
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


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


var c = $(this).closest('.row').clone();
$(this).after( c );
var count = $(this).closest('.row').find('.btn-container').length;

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

enter image description here


I tried ..

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 Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download