matrix
matrix

Reputation: 11

How to manipulate div style with javascript?

<!DOCTYPE html>
<html>
    <head>
        <title>
        </title>
        <style>
        div
        {
            width:5em;
            height:5em;
            background-color:yellow;
        }
        </style>
    </head>
    <body>
        <div id="div">
        </div>
        <script>
        window.onload = function() {
        var x;
        x = document.getElementByID("div");
        x.style.width = '9em' ;
        x.style.backgroundColor = "green";
    };

        </script>
    </body>
</html>

What im doing wrong ? I want to change div properties like width or background color with javascript but it's not working.

Upvotes: 1

Views: 1542

Answers (4)

Daksh
Daksh

Reputation: 986

You're using getElementByID. The correct method is getElementById.

Your script should look something like this:

window.onload = function() {
  var x;
  x = document.getElementById("div");
  x.style.width = '9em';
  x.style.backgroundColor = "green";
};

Upvotes: 2

orabis
orabis

Reputation: 2799

Change getElementByID to getElementById.

window.onload = function() {
  var x;
  x = document.getElementById("div");
  x.style.width = '9em';
  x.style.backgroundColor = "green";
};

If you want to search by the tag name, you can directly use getElementsByTagName("div") instead of assigning an id of the value div. But bear in my mind that it will return all div elements; i.e. a collection of elements.

Upvotes: 0

Momin
Momin

Reputation: 3320

JavaScript Syntax Error ! Here is the update...........

<!DOCTYPE html>
<html>

<head>
    <title>
    </title>
    <style>
    /* div {
        width: 5em;
        height: 5em;
        background-color: yellow;
    } */
    </style>
</head>

<body>
    <div id="div">
    </div>
    <script>
    
        var x = document.getElementById("div");
        x.style.width = "9em";
        x.style.height = "9em";
        x.style.display = "block";
        x.style.backgroundColor = "green";

    </script>
</body>

</html>

Upvotes: 0

Dinesh undefined
Dinesh undefined

Reputation: 5546

change getElementByID to getElementById

<!DOCTYPE html>
<html>
    <head>
        <title>
        </title>
        <style>
        div
        {
            width:5em;
            height:5em;
            background-color:yellow;
        }
        </style>
    </head>
    <body>
        <div id="div">
        </div>
        <script>
        window.onload = function() {
        var x;
        x = document.getElementById("div");
        x.style.width = '9em' ;
        x.style.backgroundColor = "green";
    };

        </script>
    </body>
</html>

Upvotes: 3

Related Questions