jQuery – find total number of DOM elements

To get total DOM elements including children use the following code (this includes root html element also)

$('*').length

To get all DOM elements in body (excludes body itself)

$('body *').length

Here is sample code:

<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<div id="count1">-</div>
<div id="count2">-</div>
<script type="text/javascript">
  var str1= $('*').length;
  var str2= $('body *').length;
  str1 += " => ";
  str2 += " => ";
  $('*').each(function(){
    str1 = str1 + this + " | ";
  });
  $('body *').each(function(){
    str2 = str2 + this + " | " ;
  });
  $('#count1').text(str1);
  $('#count2').text(str2);
</script>
</body>
</html>
refresh

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments