Search code examples
javascriptcode-generation

Create a drop down list with options through document.createElement?


What I want to achieve is simple: when you press a button, it creates a select element with options. I can do the select element fine, but the option, not so much. I've tried numerous things. Here's the code that I used, with some comments to help out.

 <!--This is the element that we append the JavaScript to. The code that achieves the task is at the bottom.-->
<p id="clonePanel"></p>
<script>
//Don't worry about the first pid stuff.
var pid = 0;
function dupPan() {
    pid++;
    //Here we create a "p" element. The following code is the element's content and specs.
    var newPanel = document.createElement("p");
    newPanel.id=pid;
    //Here we create a "select" element (a drop down list).
    var newList = document.createElement("select");
    //Here we create a text node.
    var newListData = document.createTextNode("Example of option");
    //Here we append that text node to our drop down list.
    newList.appendChild(newListData);
    //Here we append our list to our "p" element.
    newPanel.appendChild(newList);
    //Finally, we append the "p" element to the document, or the "clonePanel" p element.
    document.getElementById("clonePanel").appendChild(newPanel);
}
</script>

Hopefully the comments helped out. What's supposed to happen is that a select element is generated along with a text node. Then the two are appended together. Finally, all that stuff is appended to a p element, which is finally placed into the document. I know I'm doing something wrong.

I think that my method of creating a text node isn't correct. I think there's something else. If you know the answer could you please tell me the correct line of code? That would be great. And yes, I HAVE looked at any sources I can find for help but to no avail.

Thanks for reading and helping me out!


Solution

  • You're appending a text node to a select, which isn't right. You should append an option instead:

    var newListData = new Option("my label", "my value");
    //Here we append that text node to our drop down list.
    newList.appendChild(newListData);
    

    You can instantiate the Option like above as a shortcut, or you can use document.createElement('option') to do it the long way.

    It can be simplified further by losing the variable and just directly appending new options:

    newList.appendChild(new Option("my label 1", "my value 1"));
    newList.appendChild(new Option("my label 2", "my value 2"));
    newList.appendChild(new Option("my label 3", "my value 3"));