w3resource

jQuery: Count child elements using jQuery

jQuery Practical exercise Part - I : Exercise-38

Count child elements using jQuery.

Note: Count number of ‘p’ elements from the following :

<body>
<div id="selected">
<p>Red</p>
<p>White</p>
<p>Green</p>
<p>Black</p>
<p>Blue</p>
<p>Orange</p>
</div>
</body>

Sample Solution:

HTML Code :

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-git.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Count child elements using  jQuery.</title>
</head>
<body>
<div id="selected">
<p>Red</p>
<p>White</p>
<p>Green</p>
<p>Black</p>
<p>Blue</p>
<p>Orange</p>
</div>
</body>
</html>

JavaScript Code:

var count = $("#selected p").length;
console.log(count);

See the Pen jquery-practical-exercise-38 by w3resource (@w3resource) on CodePen.


Contribute your code and comments through Disqus.

Previous: Add a CSS class using jQuery.
Next: Restrict "number"-only input for textboxes including decimal points.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/jquery-exercises/part1/jquery-practical-exercise-38.php