Skip to content
Advertisement

Receive “Cannot set properties of null” error when changing SELECT options using JS

I wrote a script to change the options of a second SELECT element based on the first SELECT element options. But the issue is whenever I try to change the second SELECT options, the console gives me the following error. Important: This is a tiny snippet of code from my entire script and page.

Uncaught TypeError: Cannot set properties of null (setting ‘innerHTML’)

My HTML code

<select id="field_option-1">
    <option value="first">First option</option>
    <option value="second">Second option</option>
    <option value="third">Third option</option>
</select>

<select id="field_option-2">
    <option value="">Select one</option>
</select>

My JS code

var select1 = document.getElementById("field_option-1");
var select2 = document.getElementById("field_option-2");

select1.addEventListener('change', function(){
    var selectValue = this.value;
    if(selectValue == "first"){
        select2.innerHTML = "<option value='new1'>New option 1</option>";
    }
    else if(selectValue == "second"){
        select2.innerHTML = "<option value='new2'>New option 2</option>";
    }
    else if(selectValue == "third"){
        select2.innerHTML = "<option value='new3'>New option 3</option>";
    }
});

I tested this code in localhost and it works perfectly. But after I upload it to the server, the console is showing that error.

Advertisement

Answer

It’s possible that this JS code runs before the select tags are rendered, it depends on where the script tag linking this file is located. In any case, you can fix this by adding the defer attribute to the script tag if it has the src attribute, or by placing it at the end of the body tag.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement