Mado Baker
Mado Baker

Reputation: 109

document.getElementById wont give me "style" to change background color

So I have a function that "rolls" a dice, and I'm using netbeans to code my program, so when I write "document.getElementById." i dont get the "style" option, rather the only "s" is "seal".... I tried ignoring that and writing it either way, still didn't work, here's my code:

    <script>
        function roll()
        {
            var firstDie = document.getElementById("dice1");
            var secondDie = document.getElementById("dice2");

            firstDie.innerHTML = Math.floor(Math.random() * 7);
            secondDie.innerHTML = Math.floor(Math.random() * 7);

            if (firstDie>secondDie)
            {
                document.getElementById("dice1").style.backgroundColor = "green";
            }
        }
    </script>
</head>
<body>
    <div class="game">
        <div id="dice1" class="dice">0</div>
        <div id="dice2" class="dice">0</div>

        <div id="feed" class="feed">
        <br><br>
        <button onclick="roll()" id="rollButton" class="rollButton">Roll</button>
        </div>
    </div> 

Upvotes: 0

Views: 907

Answers (2)

AshBringer
AshBringer

Reputation: 2673

It's because you are not parsing to integer the content of div value :

        var a  = Math.floor(Math.random() * 7);
        var b = Math.floor(Math.random() * 7);
        firstDie.innerHTML = a;
        secondDie.innerHTML = b;

        if (a>b)
        {
            document.getElementById("dice1").style.backgroundColor = "green";
        }
    }

http://jsfiddle.net/bnspfg7p/5/

Upvotes: 1

plalx
plalx

Reputation: 43718

It's just not entering the if statement because domElement > otherElement would be false.

document.createElement('div') > document.createElement('div') //false

What you want is:

var firstDieValue = Math.floor(Math.random() * 7),
    secondDieValue = Math.floor(Math.random() * 7);

firstDie.innerHTML = firstDieValue;
secondDie.innerHTML = secondDieValue;

if (firstDieValue > secondDieValue) { ... }

Also, consider extracting your dice rolling strategy e.g.:

var diceRoll = randomDiceRoll(2),
    firstDieValue = diceRoll[0],
    secondDieValue = diceRoll[1];

function randomDiceRoll(diceCount) { 
    return Array.apply(0, Array(diceCount)).map(function () { 
        return Math.floor(Math.random() * 7); 
    }); 
}

Upvotes: 2

Related Questions