Tadej Bogataj Tadej Bogataj - 11 days ago 6
jQuery Question

Counting the number of sections in a HTML file

Hy,
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
console.log(number);


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

Any ideas?

Dai Dai
Answer

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 );
} );
Comments