Javascript DOM How to - Chain getElementById and getElementByClassName








Question

We would like to know how to chain getElementById and getElementByClassName.

Answer


<!DOCTYPE html>
<html>
<head>
</head><!--from  ww w  . jav  a 2s.  c  o m-->
<body>
  <div id="productPriceContainer">
    <div class="price">Asd</div>
    <div class="price">Asd</div>
  </div>
  <script>
    var elements = document.getElementById("productPriceContainer").getElementsByClassName("price");
    for (var i = 0; i < elements.length; i++) {
      elements[i].innerHTML = "Asdf" + i;
    }
</script>
</body>
</html>

The code above is rendered as follows: