Bianca
Bianca

Reputation: 93

Basic CSS manipulation using JavaScript

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".

Upvotes: 1

Views: 1639

Answers (3)

Andreas Louv
Andreas Louv

Reputation: 47099

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

Upvotes: 0

Mike Samuel
Mike Samuel

Reputation: 120516

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.

Upvotes: 1

mgiuffrida
mgiuffrida

Reputation: 3569

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.

Upvotes: 4

Related Questions