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
const element = document.getElementsByClassName("card-body")
should beconst element = document.getElementsByClassName("card-body")[0]
sincegetElementsByClassName()
returns an array:You can use the new function
querySelector
andquerySelectorAll
.Example:
Reference
Document.querySelector()