The following example demonstrates how to Append a Child Node in JavaScript

Programmingempire

Example Code to Demonstrate How to Append a Child Node in JavaScript

At first, we create a function f1() that executes when the user clicks on the button. Further, within the function, first we accept a string from the user using the prompt() function. After that, we retrieve the select element with getElementById() method. Basically, the createElement() function creates a node. So, we create an option node. Also, we need to create a text node using the createTextNode() function that contains the string. Then, we can use the appendChild() function that appends the text node to the option element. Lastly, we call the appendChild() function to append the option element to the select element.

<html>
<head>
  <title>Append a Child Node</title>
  <script>
     function f1()
     {
        str=prompt("Enter a Course Name...");
        var v=document.getElementById("s1");
        var v1=document.createElement("OPTION");
        var t=document.createTextNode(str);
        v1.appendChild(t);
        v.appendChild(v1);
     }
  </script>
</head>
<body>
  <div style="margin: 50px; padding: 20px; text-align: center;
      font-size: 20px;background-color:#aa9922;color:99ffaf;"><br/><br/>
      <select id="s1">
        <option disabled selected>Select a Course...</select>
      </select><br/><br/>
      Click on the following button to add acourse name to the above list       <br/><br/>
      <button onclick="f1()">Add</button>
  </div>
</body>
</html>

Output

The Output of the Example to Demonstrate How to Append a Child Node in JavaScript
The Output of the Example to Demonstrate How to Append a Child Node in JavaScript

Further Reading

Python List Practice Exercise

programmingempire