The getElementsByClassName()
method returns
elements with the specified class name, as a NodeList object.
getElementsByClassName |
Yes | 9.0 | Yes | Yes | Yes |
document.getElementsByClassName(classname)
Parameter | Type | Description |
---|---|---|
classname | String | Required. The class name of the elements. |
A NodeList object, representing a collection of elements with the specified class name.
The following code shows how to get all elements with the specified class name
<!DOCTYPE html>
<html>
<body>
<div class="example">First</div>
<div class="example">Second</div>
<button onclick="myFunction()">test</button>
<!--from www. jav a2 s. c o m-->
<script>
function myFunction() {
var x = document.getElementsByClassName("example");
x[0].innerHTML = "Hello World!";
}
</script>
</body>
</html>
The code above is rendered as follows:
The following code shows how to get all elements with both the "example" and "color" classes.
<!DOCTYPE html>
<html>
<body>
<div class="example">A</div>
<div class="example color">B</div>
<div class="example color">C</div>
<button onclick="myFunction()">test</button>
<!-- w w w. j a va 2 s .c o m-->
<script>
function myFunction() {
var x = document.getElementsByClassName("example color");
x[0].style.backgroundColor = "red";
}
</script>
</body>
</html>
The code above is rendered as follows:
The following code shows how to get the count of elements with class="example".
<!DOCTYPE html>
<html>
<body>
<div class="example">A</div>
<div class="example">B</div>
<button onclick="myFunction()">test</button>
<p id="demo"></p>
<!-- ww w .j ava 2s . c om-->
<script>
function myFunction() {
var x = document.getElementsByClassName("example");
document.getElementById("demo").innerHTML = x.length;
}
</script>
</body>
</html>
The code above is rendered as follows:
The following code shows how to change the background color of all elements with class="example":
<!DOCTYPE html>
<html>
<head>
<style>
.example {<!--from w ww. j a va2 s.c o m-->
border: 1px solid black;
margin: 5px;
}
</style>
</head>
<body>
<div class="example">A</div>
<div class="example">B</div>
<p class="example">C</p>
<p>This is a <span class="example">span</span>.</p>
<button class="example" onclick="myFunction()">test</button>
<script>
function myFunction() {
var x = document.getElementsByClassName("example");
var i;
for (i = 0; i < x.length; i++) {
x[i].style.backgroundColor = "red";
}
}
</script>
</body>
</html>
The code above is rendered as follows: