jQuery: Count all elements within a division
jQuery Fundamental - I : Exercise-18
Using jQuery count all elements within a division.
<body> <div id="iddiv"> <span>This is a span</span> <p>This is a Paragraph</p> <button id="button1">Click to see the effect</button> </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 all elements within a division.</title>
</head>
<body>
<div id="iddiv">
<span>This is a span</span>
<p>This is a Paragraph</p>
<button id="button1">Click to see the effect</button>
</div>
</body>
</html>
CSS Code:
button {
display: block;
margin: 20px 0 0 0;
clear: both
}
span, p {
width: 160px;
height: 40px;
float: left;
padding: 10px;
margin: 10px;
background-color: #B0E0E6
}
JavaScript Code :
$('#button1').click(function(){
var elementCount = $( "#iddiv" ).find( "*" ).css( "border", "2px solid blue" ).length;
$( "body" ).prepend( "" + elementCount + " element(s) found" );
});
See the Pen jquery-fundamental-exercise-18 by w3resource (@w3resource) on CodePen.
Contribute your code and comments through Disqus.
Previous: Using jQuery count every element (including head, body, etc.) in the document.
Next: Using jQuery click the button to animate the paragraph element with a number of different properties.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics