Show Output
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>JavaScript Select Element by Class Name</title> <style> .box { height: 50px; background: #ddd; margin: 20px; } .box.bordered{ border: 5px solid #333; } </style> </head> <body> <div class="box"></div> <div class="box bordered"></div> <div class="box"></div> <div class="box bordered"></div> <div class="box"></div> <script> var boxes = document.getElementsByClassName("box"); // Select first box and style it with red background boxes[0].style.background = "red"; /* Select elements having both "box" and "bordered" class and style them with yellow background */ var borderedBoxes = document.getElementsByClassName("box bordered"); for(var i = 0; i < borderedBoxes.length; i++){ borderedBoxes[i].style.background = "yellow"; } // Select last element and style it with green background boxes[boxes.length - 1].style.background = "green"; </script> </body> </html>