Sera Holmes
Sera Holmes

Reputation: 15

setting div background with javascript

I know this is a completely basic question, but I cannot figure it out.

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>omglol</title>
    </head>
    <body>
        <div id="div2"> 
            <p> hello there you silly unicorn </p>
        </div>
        <script> 
            document.getElementById('div2').bgColor='blue'; 
        </script>
    </body>
</html>

So then by my reckoning, this should be changing the background of div2 blue? This is not the case sadly. I am most distressed and considering listening to Justin Bieber.

Upvotes: 0

Views: 140

Answers (7)

Jeff Noel
Jeff Noel

Reputation: 7618

Explanation

bgColor is deprecated (MDN).


Solution

See JavaScript DOM Element style property documentation.

The proper way to change the background color of an element is to use the style object and to edit its backgroundColor property:

JavaScript

var div2 = document.getElementById('div2');
div2.style.backgroundColor = "blue";

In JavaScript, backgroundColor corresponds to the CSS property background-color. JavaScript does not allow hyphens in names, so "camelCase" is used instead. (MDN)

Upvotes: 1

Nidhin Joseph
Nidhin Joseph

Reputation: 1481

You could use:

document.getElementById('div2').style.background='blue';

Upvotes: 0

Pranav Singh
Pranav Singh

Reputation: 20141

Please consider adding it to function pageLoad() like :

<script> 
    function pageLoad()
    {
        document.getElementById('div2').style.backgroundColor = 'blue';
    }
</script> 

Upvotes: 0

Safeer
Safeer

Reputation: 184

Here..

document.getElementById('div2').style.backgroundColor = '#000000';

Upvotes: 0

Vivek Sadh
Vivek Sadh

Reputation: 4268

Using Pure JavaScript:-

document.getElementById('div2').style.backgroundColor = 'Color Code';

Using Jquery:-

$('#div2').css('background-color','color code');

Upvotes: 0

Sergio
Sergio

Reputation: 28845

Try this:

document.getElementById('div2').style.backgroundColor = "#00F"

Upvotes: 0

mohkhan
mohkhan

Reputation: 12325

Do this...

document.getElementById('div2').style.backgroundColor = 'blue';

Upvotes: 2

Related Questions