Javascript DOM HTML Element getElementsByClassName() Method

Introduction

Change the text of the first list item with class="child" in a list with class="example":

Click the button to change the text of the first list item.

View in separate window

<!DOCTYPE html>
<html>
<body>
<ul class="example">
  <li class="child">Coffee</li>
  <li class="child">Tea</li>
</ul>/* w  ww  . ja v a 2s  .c o  m*/
<button onclick="myFunction()">Test</button>
<script>
function myFunction() {
  var list = document.getElementsByClassName("example")[0];
  list.getElementsByClassName("child")[0].innerHTML = "Milk";
}
</script>

</body>
</html>

The getElementsByClassName() method returns a collection of an element's child elements with the specified class name as a NodeList object.

The NodeList object represents a collection of nodes.

The nodes can be accessed by index numbers. The index starts at 0.

element.getElementsByClassName(classname);

Parameter Values

Parameter Type Description
classname String Required. The class name of the child elements you want to get.

To search for multiple class names, separate them with spaces, like "child test".

The elements in the returned collection are sorted as they appear in the source code.




PreviousNext

Related