Search code examples
javascriptif-statementundefinedundefined-function

Inexplicable "Undefined is not a function" error — caused by "getElementsById"


I have spent the last few hours trying to debug this Javascript. The first if block executes just fine, but when I try to execute the second if statement, I get an "undefined is not a function" error message.

I have checked JSLint and JSHint, and tried commenting out parts of my code to no avail. Any help would be much appreciated.

var nimbus_char_count = 0;
var nimbus_line_count = 1;
var i = 2;
var j = 2;

//This block executes fine
function set_char(increment) {
    //Test success cases
    if (increment === 1 && nimbus_char_count < 3) {
        nimbus_char_count = nimbus_char_count + 1;
        $("#nimbus_char" + (nimbus_char_count - 1)).addClass("nimbus_drop");
    } else if (increment === -1 && nimbus_char_count > 0) {
        nimbus_char_count = nimbus_char_count - 1;
        $("#nimbus_char" + nimbus_char_count).removeClass("nimbus_drop");
    } else {
        nimbus_flash_red();
    }
}
//This block throws a "undefined is not a function"
function set_lines(increment) {
    if (increment === 1 && nimbus_line_count < 4) {
        nimbus_line_count = nimbus_line_count + 1;
        for (i = 2; i >= 0; i = i - 1) {
            $().getElementsById("#nimbus_char").addClass("nimbus_drop" + i);
        }
    } else if (increment === -1 && nimbus_char_count > 1) {
        nimbus_char_count = nimbus_char_count - 1;
        for (j = 2; j >= 0; j = j - 1) {
            $().getElementsById("#nimbus_char").addClass("nimbus_drop" + j);
        }
    } else {
        nimbus_flash_red();
    }
}

Solution

  • $().getElementsById("#nimbus_char") is not valid jQuery.

    I think you mean $("#nimbus_char")