Reputation: 3967
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
Reputation: 3804
Include the code in $( document ).ready
$( document ).ready(function() {
var n = $("li").length;
alert(n);
});
Upvotes: 1
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