Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the count of subchild inside the parent div in javascript or in Jquery?

I don't know how to count the div's of subchildren inside the parent div maybe someone can help me with this. I'm not that good in javascript or in Jquery.

Here's my code:

$(function () {
    var parent = document.getElementById('parent').children;
    var cnt = 0;
    if (parent) {
        var match = 'child';
        for (var i = 0; i < parent.length; i++) {
            var temp = parent[i].getAttribute('id');
            if (temp.indexOf(match) == 0) {
                cnt++;
            }
        }
    }
    console.log(cnt);
});

FIDDLE

like image 707
aldrin27 Avatar asked Dec 24 '22 14:12

aldrin27


2 Answers

You can use attribute-value selector

[id^=subchild] will select all the elements whose id value starts with(^) child.

Attribute value starts with selector.

Selects elements that have the specified attribute with a value beginning exactly with a given string.

Demo

$(function() {
  var subchildrenLen = $('#parent [id^=subchild]').length;
  $('body').append('No of children = ' + subchildrenLen);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div id="parent">
  <div id="child1">
    <div id="subchild1"></div>
  </div>
  <div id="child2">
    <div id="subchild2"></div>
  </div>
  <div id="child3">
    <div id="subchild3"></div>
  </div>
</div>

You can also use querySelectorAll with the same selector if you don't want to use jQuery.

var subchildrens = document.querySelectorAll('#parent [id^=subchild]').length;

If you want all the descendents count

var allChildrens = document.querySelectorAll('#parent div').length
like image 140
Tushar Avatar answered Dec 27 '22 04:12

Tushar


alert($('#parent').find('div[id*="subchild"]').length)

DEMO

Attribute Contains Selector [name*=”value”]

DOCUMENTATION

like image 29
guradio Avatar answered Dec 27 '22 04:12

guradio