1

I'm trying to count the section tags on a page but whenever this script runs it returns a 0. Any ideas?

    var sectionCount = $( "section").length;
    console.log(sectionCount);

The HTML I'm counting from is as follows:

    <body>
        <div class="container">
            <section class="slide">1</section>
            <section class="slide">2</section>
            <section class="slide">3</section>
        </div>
    </body>
Pokechu22
  • 4,984
  • 9
  • 37
  • 62
Jackanapes
  • 1,023
  • 1
  • 8
  • 12
  • 1
    when (or where) do you run js script? the `section` elements may not exist if you run the script in the `` when the DOM is not loaded. – Cheery Nov 19 '14 at 00:13
  • I have the script linked from my document head and its running in its own seperate file. Jsfiddle here: http://jsfiddle.net/58yuowje/ – Jackanapes Nov 19 '14 at 00:15
  • 1
    If the script is in the head and the `section` elements are in the body, then they don't exist when the script runs. – six fingered man Nov 19 '14 at 00:16
  • 4
    It runs BEFORE the rest of the page is loaded. Place the script at the end of the page or run it inside of, for example, `$(document).ready(function() { /* here */; });` – Cheery Nov 19 '14 at 00:16
  • It works [here](http://jsfiddle.net/tgp0o87v/) – Anubhav Nov 19 '14 at 00:18
  • @Anubhav, fiddle is running the script on page load change the setting to run in the head of the document. – robbmj Nov 19 '14 at 00:19
  • [It works](http://jsfiddle.net/cdanea/arqybeob/3/) – cdanea Nov 19 '14 at 00:25

1 Answers1

3

Just add a $(document).ready() clause so that it runs after the html DOM has been loaded.

$( document ).ready(function() {
  var sectionCount = $( "section").length;
  console.log(sectionCount);
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
        <div class="container">
            <section class="slide">1</section>
            <section class="slide">2</section>
            <section class="slide">3</section>
        </div>
    </body>
Wold
  • 952
  • 1
  • 13
  • 25