Reputation: 59
What is the most appropriate and cross-browser compatible way to change background color of an element using JavaScript?
<!DOCTYPE html>
<html>
<head>
<title>Demo page</title>
</head>
<body>
<h1 id="head1" style="background-color:red">This is a heading</h1>
<script>
// this one?
document.getElementById("head1").style["background-color"] = "yellow";
// this one?
document.getElementById("head1").style.backgroundColor = "yellow";
//or this one?
document.getElementById("head1").style.background = "yellow";
</script>
</body>
</html>
Upvotes: 2
Views: 2404
Reputation: 10265
There is a better method if you are using CSS class
instead of using style
.
function foo(){
document.getElementById("head1").className = "newclass";
}
h1{background:gold;}
h1.newclass{background:green;}
<h1 id="head1">This is a heading</h1>
<button onclick="foo()">Click!</button>
Upvotes: 1
Reputation: 1111
Get the element, then use the .style
attribute along with the .backgroundColor
attribute to change it:
function foo(){
document.getElementById("head1").style.backgroundColor = "yellow";
}
<!DOCTYPE html>
<html>
<head>
<title>Demo page</title>
</head>
<body>
<h1 id="head1" style="background-color:red">This is a heading</h1>
<button onclick="foo()">Click!</button>
</body>
</html>
Thus, your 2nd option is the right one.
Upvotes: 3