Ameya
Ameya

Reputation: 549

javascript appendChild not working

Here is the code I have, I am trying to append the elements in the array to a drop down select box. The code works fine until the appendChild method. I can't figure out why that one line is not working. Here is the code

</head>
<body>
    <h1> Eat Page</h1>
    <p id="test">Hi</p>
    <select id="CusineList"></select>

    <script type="text/javascript">

        var cuisines = ["Chinese","Indian"];
        var sel = document.getElementById('CuisineList');

        for(var i = 0; i <cuisines.length; i++){

            var optionElement = document.createElement("option");

            optionElement.innerHTML = cuisines[i];

            optionElement.value = i;//cuisines[i];
            //document.getElementById("test").innerHTML = cuisines.length;
            sel.appendChild(optionElement);

        }
    </script>

    <p> When </p>
</body>

</html>

Upvotes: 1

Views: 6056

Answers (3)

gaurang171
gaurang171

Reputation: 9090

When we append node using java script, after setting nodes' attributes/properties first we have to append this node into its related parent and after appending node, we can set its content or related inner HTML / text.

here is the solution for above issue:

var cuisines = ["Chinese", "Indian"];var sel = document.getElementById('CusineList');
var optionElement;
for (var i = 0; i < cuisines.length; i++) {
    optionElement = document.createElement("option");
    optionElement.value = i;
    sel.appendChild(optionElement);
    optionElement.innerHTML = cuisines[i];
    document.getElementById("test").innerHTML = cuisines.length;
}

I have created a bin with the solution on http://codebins.com/codes/home/4ldqpcn

Upvotes: 0

ace
ace

Reputation: 6825

There's a typo on

var sel = document.getElementById('CuisineList');

This should be

var sel = document.getElementById('CusineList');

Or change your html. From

<select id="CusineList"></select>

To

<select id="CuisineList"></select>

Upvotes: 0

xdazz
xdazz

Reputation: 160923

You have spell miss.

Your id is CusineList, but when you use CuisineList to select.

Beside that, your code works.

Upvotes: 4

Related Questions