In the code that is inside the if it does not work but when I take it out and put the code in the console it works, someone who can help me there:
Welcome to the community; I hope I can help you, but as Alfredo says, it is always good that you copy and paste your code as text, so that it is easy for us to copy and analyze.
The problem is the position where you run the script. First the script is executed and then it creates the DOM; You can use the OnLoad event, or add a listener for it, or as easy as possible, you can put the script at the end of the body, in this way.
<!DOCTYPE html>
<html>
<head>
<title>document</title>
</head>
<body id="body">
<script>
let color = prompt("Elija azul con A) o amarillo con a)");
if(color=='A'){
document.getElementById("body").style.backgroundColor = "blue";
}
if(color=='a'){
document.getElementById("body").style.backgroundColor = "yellow";
}
</script>
</body>
</html>
I hope it serves you.
You can write a more professional and flexible code with the following advantages:
"r" : "red"
in the array, for example). prompt
that forces you to write valid values. cssColor
will be defined by looking in the color array for the entered value. If it does not exist, it will give the background a default value ( gray
in the code example). body
allows having an event onload
, we can use add our function to that event and nothing else ... I hope you find it useful.
function changeBackground() {
var arrColors = {
"A": "blue",
"a": "yellow"
};
var promptMessage = "Escribe [A] para Azul o [a] para amarillo";
var promptWrited = prompt(promptMessage, "");
while (!promptWrited) {
promptWrited = prompt(promptMessage, "");
}
var cssColor = (typeof arrColors[promptWrited] == "undefined") ? "gray" : arrColors[promptWrited];
document.body.style.background = cssColor;
}
<body onload="changeBackground();">