Get all <p> elements in the document with class="example", and set the background of the first <p> element:
Click the button to add a background color to the first p element (index 0) in the document with class="example".
<!DOCTYPE html> <html> <body> <h2 class="example">A heading with class="example"</h2> <p class="example">A paragraph with class="example".</p> <p class="example">Another paragraph with class="example".</p> <button onclick="myFunction()">Test</button> <script> function myFunction() {//from ww w .j ava 2 s . c om var x = document.querySelectorAll("p.example"); x[0].style.backgroundColor = "red"; } </script> </body> </html>