Javascript examples for DOM:Document getElementsByClassName
The getElementsByClassName() method returns elements with the class name as a NodeList object.
The nodes can be accessed by index numbers. The index starts at 0.
Parameter | Type | Description |
---|---|---|
classname | String | Required. |
To search for multiple class names, separate them with spaces, like "test class1 class2".
A NodeList object, representing elements with the specified class name.
The elements in the returned collection are sorted as they appear in the source code.
The following code shows how to Get all elements with the specified class name:
<!DOCTYPE html> <html> <head> <style> div {/*from w w w. j av a 2 s . c o m*/ border: 1px solid black; margin: 5px; } </style> </head> <body> <div class="example"> <p>test</p> </div> <div class="example color"> <p>P element</p> </div> <div class="example color"> <p>P element in second div</p> </div> <button onclick="myFunction()">Test</button> <script> function myFunction() { var x = document.getElementsByClassName("example color"); x[0].style.backgroundColor = "red"; } </script> </body> </html>