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>
(1 votes)
Loading...

Similar Posts

Subscribe
Notify of
18 Answers
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Babelfish
1 year ago

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:

bodyElement.style.backgroundColor = "green";

Please look at the Doku:

https://www.w3schools.com/jsref/prop_style_backgroundcolor.asp

ZaoDaDong
1 year ago

You need to update the bodyElement variable if you want to edit it.

Like that.




    
    
    Beta
     

    
                           
ZaoDaDong
1 year ago
Reply to  SusgUY446

that ultimately makes the same.

Rolajamo
1 year ago

Try this:




    
    
    Beta  

    
ZaoDaDong
1 year ago
Reply to  SusgUY446

what does not work? What do you expect to happen?

Babelfish
1 year ago

But does not work as it should and was expected.

ZaoDaDong
1 year ago

“works” already, is just zero.

Babelfish
1 year ago

document.querySelector(“body”)

… does not work in the HEAD because the BODY element does not exist in the DOM.

CSANecromancer
1 year ago

Because there’s a mistake.

ZaoDaDong
1 year ago
Reply to  SusgUY446

in the code.

CSANecromancer
1 year ago
Reply to  SusgUY446

Up there.

(Why should I try the answer if you are too lazy to say, WAS not working?)