1

I'm currently learning JavaScript, but I'm very weak on the fundamentals. I'm trying to write a function that changes the background color when a link is clicked, can you please advise me on what I'm doing wrong?

<head>

<script type="text/javascript">

function change()
{
var abra = document.getElementbyId("body").style;
abra.background-color = "black";

}
</script>

</head>

<body>

<div id="body" style="background-color: red;">
<a href="#" id="test" onclick="return change()">Test</a>
sdfdsfsdfds

</div>

</body>

EDIT: For clarification, I was trying to change the background color of the DIV "body".

0

3 Answers 3

4

The property you're looking for is backgroundColor:

abra.backgroundColor = "black";

In general, Javascript uses the corresponding camelCase for CSS style properties. See a list of some properties for examples.

Sign up to request clarification or add additional context in comments.

Comments

1

Instead of

var abra = document.getElementbyId("body").style
abra.background-color = "black";

try

document.body.style.backgroundColor = "black";

document.getElementbyId("body")

looks for an element with ID body, and

abra.background-color

is the same as

(abra.background) - color

which will probably result in an error telling you there is no var named color.

1 Comment

This changes the bgcolor of the entire body, not just the div that happens to have the id "body". OP may want to achieve one or the other, just note that they're different.
0

use camelCase:

background-color => backgroundColor

var abra = document.getElementById("body").style;
abra.backgroundColor = "black";

But if you want the body tag use:

document.getElementsByTagName("body")[0]

or

document.body // recommended

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.