Search code examples
javascriptif-statementinnerhtml

JS if statement - innerHTML


function colorize(){
    for(i = 1; i<=8; i++)
    {
        var id = document.getElementById('op' + i);

        var stat = id.innerHTML;
        document.write(stat + " ");
        if(stat == 1)
        {
            id.innerHTML = "<div style='background:#00FF00; width: 20px; height: 20px; border-radius: 15px;'></div>";
        }
        else{
            id.innerHTML = "<div style='background:#FF0000; width: 20px; height: 20px; border-radius: 15px;'></div>";
        }
    }
}

It should check if there is a 1 or 0 and replace it with a green or red circle, but I only get red circles.

"stat" printing gave me an " 0 0 0 1 1 1 1 1" but it seem to be not working with the if statement. Does anybody know why?


Solution

  • If stat.length always equals 1:

    if(stat[0]=='1'){
    

    If all you are looking for is a 1 in stat:

    if(stat.match(/1/)){//contains a 1, may contain more