jQuery: Count every element in the document

jQuery Fundamental - I : Exercise-17

Using jQuery count every element (including head, body, etc.) in the document.

Sample solution :

HTML Code :

<!DOCTYPE html>
  <script src="https://code.jquery.com/jquery-git.js"></script>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Count  every element (including head, body, etc.) in the document.</title>
  <div>This is division</div>
  <span>This is a span</span>
  <p>This is a Paragraph</p>
  <button id="button1">Click to see the effect</button>

CSS Code:

 button {
    display: block;
    margin: 20px 0 0 0;
    clear: both

   div, span, p {
    width: 160px;
    height: 40px;
    float: left;
    padding: 10px;
    margin: 10px;
    background-color: #B0E0E6

JavaScript Code :


var elementCount = $( "*" ).css( "border", "3px solid blue" ).length;
$( "body" ).prepend( "<h2>" + elementCount + " elements found</h3>" );

Used Methods :

  • All Selector ("*") : Selects all elements.

See the Pen jquery-fundamental-exercise-17 by w3resource (@w3resource) on CodePen.

Contribute your code and comments through Disqus.

Previous: Attach a function to be executed whenever an Ajax request completes successfully.
Next: Using jQuery count all elements within a division.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Share this Tutorial / Exercise on : Facebook and Twitter