+ 1

why is the box not changing color when the button is clicked

<html> <head> </head> <body> <p id="tryIt"> </p> <button type="button" onclick="digit(this)">Touch Me</button> <style type="text/css"> #tryIt{height:17vh; width:35vw; background:rgb(145,145,145);} </style> <script> function digit(element) {var e=document.getElementById("tryIt").element.style.backgroundColor.innerHTML; if(e=="green") {document.getElementById("tryIt").element.style.backgroundColor.innerHTML ="blue"} else{document.getElementById("tryIt").element.style.backgroundColor.innerHTML="orange"} } </script> In the code above i am targeting the paragraph to change not the button?

20th Jul 2020, 11:27 AM
Anyanwu Johnbosco Chima
Anyanwu Johnbosco Chima - avatar
3 Answers
+ 1
Code: <html> <head> </head> <body> <p id="tryIt"> </p> <button type="button" onclick="digit()">Touch Me</button> <style type="text/css"> #tryIt{height:17vh; width:35vw; background:rgb(145,145,145);} </style> <script> const p = document.getElementById('tryIt'); let digit = () => { let color = p.style.backgroundColor; if(color == "orange") { p.style.backgroundColor = "blue"; } else { p.style.backgroundColor = "orange"; } } //I replace green on orange for the fun u can input your colors </script> <!--In the code above i am targeting the paragraph to change not the button?--> </body> </html>
22nd Jul 2020, 7:01 AM
Dmitriy Alekseenko
Dmitriy Alekseenko - avatar
+ 1
I think I help you man
22nd Jul 2020, 7:01 AM
Dmitriy Alekseenko
Dmitriy Alekseenko - avatar
0
document.getElementById("tryIt").style.backgroundColor; is the correct way to get and set the backgroundColor of an element. remove the .element and .innerHTML part
20th Jul 2020, 8:57 PM
JME