...
for(let g = 1; g < 6; g++) {
for(let p = 1; p < 6; p++) {
if(document.getElementById("sub_class_" + g + "_" + p).style.backgroundImage == "") {
if(found_pos == 0) {
empty_row = "_" + g + "_" + p;
found_pos = 1;
}
}
}
}
if(found_pos == 1) {
if(document.getElementById("sub_class" + empty_row)) {
...