Tadej Bogataj Tadej Bogataj - 1 year ago 79
jQuery Question

Counting the number of sections in a HTML file

I have a simple one page website, made from several sections. When I write a script inside of the html file it correctly gives me the number of sections. The code is this:

var number = $("#sections li").length

But when I run the exact same code from a outer file, it doesn't work.

Any ideas?

Dai Dai
Answer Source

Possible reasons:

  • Your JavaScript could be being executed before all of the HTML has been fully loaded
  • Your CSS selector and code doesn't actually tell you how many <section> elements there are, it tells you how how many <li> elements exist under <foo id="sections">, is this intentional?
  • Your code is being executed in a context where jQuery is unavailble - also, I note, you're not using anything in jQuery that makes it worthwhile.

Your code would be more portable (and faster) by using plain ol' JavaScript:

var count = document.getElementById("sections").getElementsByTagName("li").length;

Or (slightly less portable: requires modern browsers):

var count = document.querySelectorAll("#sections li").length;

More specifically:

window.addEventListener('DOMContentLoaded', function(e) {

    var count = document.querySelectorAll("#sections li").length;
    console.log( count );
} );
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download