Search code examples
javascripthtmltagschildren

Error when attempting to change child div properities


I am getting the error Uncaught TypeError: Cannot read property 'style' of null on the line document.getElementById(blueChild).style.border = "2px solid white" and I've looked on-line and haven't found a solution. Here is my code:

var scroller = function(direction, team){
    console.log("scrolling")
    if (team == "blue"){
        if (direction == "left"){
            blueCount = blueCount - 1
        }

        if (blueCount < 0){
            blueCount = 3
        }
        if (redCount < 0){
            redCount = 3    
        }

        var blueChildren = document.getElementById('blueSelector').getElementsByTagName('div')
        var blueChild = blueChildren[blueCount]
        document.getElementById(blueChild).style.border = "2px solid white"

        for (var i = 0; i < blueChildren.length; i++){
            if (i !== blueCount){
                blueChild = blueChildren[i]
                document.getElementById(blueChild).style.border = "2px solid black"
            }
        }
    }
}

scroller("left", "blue")

By the way, blueCount, redCount have global defaults of 0

Much requested HTML

<html>
<head>
    <link rel="stylesheet" href="normalize.css">
    <link rel="stylesheet" href="main.css">
    <script src="jquery.js"></script>
    <script src="rectangle.js"></script>
    <script src="main.js"></script>
</head>
<body>
    <canvas id="canvas">You're browser does not support the canvas tag. Go and get a real browser, nub</canvas>
    <div id="redSelector">
        <div class="genericButton" id="zombieRed">Zombie</div>
        <div class="genericButton" id="skeletonRed">Skeleton</div>
         <div class="genericButton" id="creeperRed">Creeper</div>
        <div class="genericButton" id="spideBlue">Spider</div>
    </div>
    <div id="blueSelector">
        <div class="genericButton" id="zombieBlue">Zombie</div>
        <div class="genericButton" id="skeletonBlue">Skeleton</div>
         <div class="genericButton" id="creeperBlue">Creeper</div>
        <div class="genericButton" id="spiderBlue">Spider</div>
    </div>
</body>

What i am trying to achieve is assessing the child elements of blueSelector and making one coloured with a white border and rest with a black border.


Solution

  • I have found a solution! turns out i defined blueCount using var blueCount and when i used the variable as an index in my array of blueChildren, blueCount is undefined and the blueChild is then undefined.

    Hope people learn from my silly mistakes xD