-1

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?

Yerko Palma
  • 9,788
  • 5
  • 31
  • 52
Tadej Bogataj
  • 309
  • 1
  • 3
  • 11

2 Answers2

2

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 );
} );
Dai
  • 110,988
  • 21
  • 188
  • 277
0

Assuming the jQuery library is included and all files that are to be run in the page are also included then there is no reason why that wouldn't work. Without seeing how your file structure is laid out or your main JavaScript file is written, it's hard to say specifically why it is failing. It would also help to know what the Error is that you are receiving.

My best guess is your executing code before the dom is ready, try this:

$(function() {
  var number = $("#sections li").length
  console.log(number);
});

Where $(function() { }); is jQuery shorthand for $(document).ready(function() { });

Turk
  • 585
  • 3
  • 20