Rahul Sarkar
Rahul Sarkar

Reputation: 89

count number of child elements in AngularJS

I went through many answers to find how to count number of child elements in Angular JS but I didn't understood. Please have a look at my simple code and suggest me super simple method of counting no of childs.

I want count the total child under <div id="myDiv"> and total span elements under <div id="myDiv">.

Here total no of child = 5 and total span elements = 3

<html>
    <body ng-app="myApp" ng-controller="myCtrl">
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

        <button ng-click="countElem()">Count</button>
        <div id="myDiv">
            <span>child 1</span>
            <span>child 2</span>
            <span>child 3</span>
            <p>child 4</p>
            <p>child 5</p>
        </div>

        <script>
            var app = angular.module("myApp", []);
                app.controller("myCtrl", function($scope){

            });
        </script>
    </body>
</html>

Upvotes: 3

Views: 4976

Answers (3)

Allen
Allen

Reputation: 182

I know this is a really old post, but this also works

var childNum = document.querySelector('#myDiv').childElementCount;

This also saves a DOM query

Upvotes: 0

Shantha Moorthy K
Shantha Moorthy K

Reputation: 5

 Your HTML like this...

<div class="row"> 
  <div class="cols">col 1</div>
  <div class="cols">col 2</div>
  <div class="cols">col 3</div>
</div>
<div class="row">
  <div class="cols">col 1</div>
  <div class="cols">col 2</div>
</div>

You can use the below script :

angular.forEach(document.querySelectorAll('.row'), function(val, key){
 angular.element(val).removeClass('row');
angular.element(val).addClass('row'+angular.element(val).children().length);
});

Upvotes: 0

Geeky
Geeky

Reputation: 7488

You can make use of querySelectorAll and get length on it

check the following snippet

 var app = angular.module("myApp", []);
 app.controller("myCtrl", function($scope) {
   $scope.countElem = function() {
     var div = document.querySelector('#myDiv');
     var spanCount = div.querySelectorAll('span').length;
     var pCount = div.querySelectorAll('p').length;
     console.log("spanCount" + spanCount);

     console.log("pCount" + pCount);
   }
 });
<html>

<body ng-app="myApp" ng-controller="myCtrl">
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

  <button ng-click="countElem()">Count</button>
  <div id="myDiv">
    <span>child 1</span>
    <span>child 2</span>
    <span>child 3</span>
    <p>child 4</p>
    <p>child 5</p>
  </div>

  <script>
  </script>
</body>

</html>

Hope it helps

Upvotes: 6

Related Questions