Element getElementsByClassName() Method - Find out how many elements with class="child" there are inside of a <div> element - Javascript DOM

Javascript examples for DOM:Element getElementsByClassName

Description

Element getElementsByClassName() Method - Find out how many elements with class="child" there are inside of a <div> element

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<head>
<style>
div {/*  w w w  .  j  a  v a 2s.  c o m*/
    border: 1px solid black;
    margin: 5px;
}
</style>
</head>
<body>

<div id="myDIV">
  <p class="child">A p element with class="child" in a div.</p>
  <p class="child">Another p element with class="child" in a div.</p>
  <p class="child">A third p element with class="child" in a div.</p>
</div>

<button onclick="myFunction()">Test</button>

<p id="demo"></p>

<script>
function myFunction() {
    var x = document.getElementById("myDIV").getElementsByClassName("child");
    document.getElementById("demo").innerHTML = x.length;
}
</script>

</body>
</html>

Related Tutorials