Warum funktioniert dieser code nicht?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Beta</title>
<script>
const bodyElement = document.querySelector("body");
function setColorBlue() {
bodyElement.background-color = "blue";
};
function setColorRed() {
bodyElement.background-color = "red";
};
function setColorGreen() {
bodyElement.background-color = "green";
}
</script>
</head>
<body>
<div class="color-picker">
<button onclick="setColorBlue()">Blue</button>
<button onclick="setColorRed()">Red</button>
<button onclick="setColorGreen()">Green</button>
</div>
</body>
</html>
What is the error message? I’m guessing that body cannot be found, as this is not yet available from the script at this point.
The easiest thing is if you move the whole script block to the end and before the closing :
A second error is that there is no background-color in Javascript:
Please look at the Doku:
https://www.w3schools.com/jsref/prop_style_backgroundcolor.asp
You need to update the bodyElement variable if you want to edit it.
Like that.
that ultimately makes the same.
Try this:
does not work
what does not work? What do you expect to happen?
But does not work as it should and was expected.
“works” already, is just zero.
document.querySelector(“body”)
… does not work in the HEAD because the BODY element does not exist in the DOM.
that the background color can be changed. but it’s done.
Because there’s a mistake.
where?
in the code.
Up there.
(Why should I try the answer if you are too lazy to say, WAS not working?)
hahahaha
Look: https://jsfiddle.net/w8tsoLr7/
I have already fixed it but thank you