skip to Main Content

new to js and trying to get a total number of input tags in a div element then display the total.

Thanks for the help and sorry if this is a repeat question.

<div class="card-body">

  <span>0</span> / <span id="total-inputs"></span>
  
  <ul>
    <li>
        <input type="checkbox" id="input-1" class="sum" value="1" >
        <label for="input-1">
          Input 1
        </label>
    </li>
    <li>
        <input type="checkbox" id="input-2" class="sum" value="1" >
        <label for="input-2">
          Input 2
        </label>
    </li>
  </ul>
</div>
const element = document.getElementsByClassName("card-body");
const nodes = element.getElementsByTagName("input");
document.getElementById("total-inputs").innerHTML = nodes.length;

Getting this error:

TypeError: element.getElementsByTagName is not a function

2

Answers


  1. const element = document.getElementsByClassName("card-body") should be const element = document.getElementsByClassName("card-body")[0] since getElementsByClassName() returns an array:

    const element = document.getElementsByClassName("card-body")[0];
    const nodes = element.getElementsByTagName("input");
    document.getElementById("total-inputs").innerHTML = nodes.length;
    <div class="card-body">
    
      <span>0</span> / <span id="total-inputs"></span>
      
      <ul>
        <li>
            <input type="checkbox" id="input-1" class="sum" value="1" >
            <label for="input-1">
              Input 1
            </label>
        </li>
        <li>
            <input type="checkbox" id="input-2" class="sum" value="1" >
            <label for="input-2">
              Input 2
            </label>
        </li>
      </ul>
    </div>
    Login or Signup to reply.
  2. You can use the new function querySelector and querySelectorAll.

    Example:

    var div = document.querySelector('div.card-body');
    var inputs = div.querySelectorAll('input');
    var inputLenth = inputs.length;
    console.log(inputLenth);
    

    Reference
    Document.querySelector()

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search