Search code examples
javascriptdomruntime-errorappendchild

JavaScript RunTime Error : appendChild() - Unexpected call to method or property in IE8


I am getting runtime JS error like : "Unexpected call to method or property". Here is the code :

    var comboInput = document.getElementById("Combo");
    var option1 = document.createElement("option");
    option1.value = "-1";
    option1.innerHTML = "--Select--";
    comboInput.appendChild(option1); //At this line debugger breaks and
                                     // throws the above error

I gone through some of similar questions on SO about this issue but still not getting the solution.

Please help.. Thanks in adv...


Solution

  • You can't append children to <input> elements.

    <option> elements can only be children of <select> elements, where <select> elements are html's version of a drop-down list (or a multiselect list depending on the attributes you give it).

    Try changing your html so that your "Combo" element is like this:

    <select id="Combo"></select>
    

    and then your code should work.

    Note though that you can set options directly in the html markup, e.g.,

    <select id="Combo">
        <option value="-1">--Select--</option>
        <option value="1">Green</option>
        <option value="2">Purple</option>
    </select>
    

    (And having put options in your html you can add additional options and/or remove options via JS.)