Robert
Robert

Reputation: 10390

JavaScript DOM change background color not working as expected

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

Upvotes: 0

Views: 793

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388316

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;

Upvotes: 1

Mritunjay
Mritunjay

Reputation: 25882

Say like bellow to get the button

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

instead of

document.colorButton.onclick = setBGColor;

Upvotes: 1

Related Questions