itamar
itamar

Reputation: 3967

Finding Number of Elements on Page (JQuery)

I am trying to simply count the number of <li> elements I have.

I am wrote this:

<script>
    var n = $("li").length;
    alert(n);
</script>

But for some reason I am getting this error in the console instead of an alert with the number of <li> elements:

Uncaught TypeError: Cannot read property 'length' of null filter:297 (anonymous function)

Upvotes: 0

Views: 132

Answers (2)

NullPointerException
NullPointerException

Reputation: 3804

Include the code in $( document ).ready

fiddle

$( document ).ready(function() {
  var n = $("li").length;
  alert(n);
});

Upvotes: 1

Sushanth --
Sushanth --

Reputation: 55740

Either move your script to the bottom of the page , just before the HTML ends or encase that in DOM Ready handler . Also it is a better idead to include jQuery from a CDN

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js">
</script>
<script>
     $(function() {
        var n = $("li").length;
        alert(n);
     });
 </script>

Upvotes: 2

Related Questions