Mohammed Badr Mohammed Badr - 2 months ago 6
HTML Question

How to change color style attribut with javascript?

This code doesn't work when I try it.

<!DOCTYPE html>
<html>
<body>
<h1 >My first java script</h1>
<p id="p2">I can change color by one click</p>
</br>
<button type="button" onclick="myFunction()">Click me</button>
<script>
function myFunction() {
document.getElementsById("p2").style.color = "yellow";
}
</script>
</body>
</html>




function myFunction() {
document.getElementsById("p2").style.color = "yellow";
}

<h1>My first java script</h1>
<p id="p2">I can change color by one click</p>
</br>
<button type="button" onclick="myFunction()">Click me</button>




Answer

It is getElementById without s.

<!DOCTYPE html>
<html>
<body>
<h1 >My first java script</h1>
<p id="p2">I can change color by one click</p>
</br>
<button type="button" onclick="myFunction()">Click me</button>
<script>
    function myFunction() {
        document.getElementById("p2").style.color = "yellow";
    }
</script>
</body>
</html>

function myFunction() {
  document.getElementById("p2").style.color = "yellow";
}
<h1>My first java script</h1>
<p id="p2">I can change color by one click</p>
</br>
<button type="button" onclick="myFunction()">Click me</button>