Javascript DOM HTML Document getElementsByClassName() Method

Introduction

Get all elements with the specified class name:

var x = document.getElementsByClassName("example");

Click the button to change the text of the first div element with class="example" (index 0).

View in separate window

<!DOCTYPE html>
<html>
<body>

<div class="example">First div element with class="example".</div>

<div class="example">Second div element with class="example".</div>
<button onclick="myFunction()">Test</button>
<script>
function myFunction() {//  www  .ja  v  a  2  s  .c om
  var x = document.getElementsByClassName("example");
  x[0].innerHTML = "Hello World!";
}
</script>

</body>
</html>

The getElementsByClassName() method returns a collection of elements with the specified class name, as an HTMLCollection object.

The HTMLCollection object represents a collection of nodes.

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

document.getElementsByClassName(classname);

Parameter Values

Parameter
Type
Description
classname

String

Required. The class name of the elements you want to get.
To search for multiple class names, separate them with spaces, like "test demo".

The getElementsByClassName() method returns an HTMLCollection object, representing a collection of elements with the specified class name.

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




PreviousNext

Related