The getElementsByClassName()
method returns a collection
of an element's child elements with the specified class name, as a NodeList object.
getElementsByClassName |
Yes | 9.0 | Yes | Yes | Yes |
element.getElementsByClassName(classname)
Parameter | Type | Description |
---|---|---|
classname | String | Required. The class name of the child elements. |
A NodeList object, representing a collection of the elements' child elements with the specified class name.
The following code shows how to change the text of the first list item.
<!DOCTYPE html>
<html>
<body>
<ul class="example">
<li class="child">A</li>
<li class="child">B</li>
</ul><!-- w ww . ja va 2 s .co 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 code above is rendered as follows:
The following code shows how to change the background color of the second element inside of a <div> element.
<!DOCTYPE html>
<html>
<head>
<style>
div {<!-- w w w . j a va2 s . c om-->
border: 1px solid black;
margin: 5px;
}
</style>
</head>
<body>
<div id="myDIV">
<p class="child">First p element</p>
<p class="child">Second p element</p>
<p class="child">Third p element</p>
</div>
<button onclick="myFunction()">test</button>
<script>
function myFunction() {
var x = document.getElementById("myDIV");
x.getElementsByClassName("child")[1].style.backgroundColor = "red";
}
</script>
</body>
</html>
The code above is rendered as follows: