0

I have:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript index</title>
</head>
<body id="body">
<input name="colorButton" type="button" value="Change background color" />

<script>
"use strict";

function setBGColor() {
    document.body.style.backgroundColor = "blue";
}

document.colorButton.onclick = setBGColor;

</script>
</body>
</html>

As you can see I am trying to change the background color of the body once the button is pressed. But I am getting the following error:

Uncaught TypeError: Cannot set property 'onclick' of undefined

2 Answers 2

1

There is no property called colorButton for document:

document.querySelector('input[name="colorButton"]').onclick = setBGColor;

You need to get the input element (since you have name use the element name).


Or add an id:

<input name="colorButton" id="colorButton" type="button" value="Change background color" />

And then:

document.getElementById('colorButton').onclick = setBGColor;
Sign up to request clarification or add additional context in comments.

Comments

1

Say like bellow to get the button

document.getElementsByName('colorButton')[0].onclick = setBGColor;    

instead of

document.colorButton.onclick = setBGColor;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.