Home > Net >  Why is the length of an html collection coming as zero?
Why is the length of an html collection coming as zero?

Time:10-05

When I am using the length property over the HTML Collection,I am getting zero...Please Correct me someone..

My HTML Code:

    <div class="container">
        <div class="header">
            <h1>To Do List</h1>
        </div>
        <div class="todos">
            <ul class="todolist">
                <li class="listItem">
                    <p>Doing Homework</p>
                </li>
                <li class="listItem">
                    <p>Doing Competitve Programming</p>
                </li>
                <li class="listItem">
                    <p>Doing Dynamic Programming</p>
                </li>
                <li class="listItem">
                    <p>Doing Robot Programming</p>
                </li>
                <li class="listItem">
                    <p>Doing DSA</p>
                </li>
            </ul>
        </div>
    </div>
</body>

MY JS Code:

function crossAdder() {
    var todolist = document.getElementsByClassName('.listItem');
    console.log(todolist.length);
}
crossAdder();

CodePudding user response:

Remove . in .listItem when you input to document.getElementsByClassName function.

It accept a class name, not a CSS selector.

function crossAdder() {
  var todolist = document.getElementsByClassName('listItem');
  console.log(todolist.length);
}
crossAdder();
<div class="container">
  <div class="header">
    <h1>To Do List</h1>
  </div>
  <div class="todos">
    <ul class="todolist">
      <li class="listItem">
        <p>Doing Homework</p>
      </li>
      <li class="listItem">
        <p>Doing Competitve Programming</p>
      </li>
      <li class="listItem">
        <p>Doing Dynamic Programming</p>
      </li>
      <li class="listItem">
        <p>Doing Robot Programming</p>
      </li>
      <li class="listItem">
        <p>Doing DSA</p>
      </li>
    </ul>
  </div>
</div>
</body>

CodePudding user response:

function crossAdder(){

   //Use query selector if you are using .listItem
   var todoList = document.querySelectorAll(".listItem")

   //If you are using getElementsByClassName don't use the dot only need just listItem
   var todoList = document.getElementsByClassName("listItem")

   console.log(todoList)
}

  • Related