Cannot read property 'options' of null JS

I’m having some troubles with my JS code. I have created a drop-down list with JS and a button next to it to get the selected value from the drop-down list and use it for a calculation.
However, when clicking on the button, for some reason the text of the selected option cannot be read.

Code below

                for (let i = 0;  i < neededDays - 1; i++){
                    let selectBreak = document.createElement("SELECT");
                    selectBreak.id = "selectBreak" + i;
                    document.getElementById("eta").appendChild(selectBreak);

                    let arrayBreakOptions = ["9", "11", "24", "45"];
                    for (let j = 0; j <arrayBreakOptions.length; j++){
                        let option = document.createElement("OPTION");
                        option.value = arrayBreakOptions[j];
                        option.text = arrayBreakOptions[j];
                        if (option.value == 11){
                           option.setAttribute("selected", "selected");
                        }
                    document.getElementById("selectBreak" + i).appendChild(option);
                        
                    let btnChangeBreakHours = document.createElement("BUTTON");
                    btnChangeBreakHours.id = "btnChangeBreakHours";
                    btnChangeBreakHours.innerHTML = "Recalculate";
                    btnChangeBreakHours.setAttribute("type", "button");
                    document.getElementById("eta").appendChild(btnChangeBreakHours);
                    document.getElementById("eta").appendChild(document.createElement("BR"));
                    let minutesDayBreak = 0;
                    btnChangeBreakHours.onclick = function changeBreakHours(){
                        let sel = document.getElementById("selectBreak" + i);
                        let selectedValueBreak = sel.options[sel.selectedIndex].text;
                        minutesDayBreak = selectedValueBreak * 60;
                    }
                }

I found similiar problems to mine but the issue with them was that there were typos in the code. I already checked mine and it seems to me that there are no typos.

The error is

TypeError: Cannot read property ‘options’ of null at HTMLButtonElement.changeBreakHours

Do you have any tips and suggestions what I am missing?

61 thoughts on “Cannot read property 'options' of null JS”

Leave a Comment