Horje

How to use JavaScript to add a yellow background color to the first element with class="example" (index 0)

First div element with class="example". Second div element with class="example". Click the button to add a yellow background color to the first div element with class="example" (index 0).
index.html
Example: HTML
<!DOCTYPE html>
<html>
<body>

<div class="example">First div element with class="example".</div>
<div class="example">Second div element with class="example".</div>

<p>Click the button to add a yellow background color to the first div element with class="example" (index 0).</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
  let x = document.getElementsByClassName("example");
  x[0].style.backgroundColor = "yellow";
}
</script>

</body>
</html>

Output should be:

How to use JavaScript to add a yellow background color to the first element with class="example" (index 0)




Type:
html
Category:
Web Tutorial
Sub Category:
HTML Global Attributes
Uploaded by:
Admin