SubhanUllah Posted October 10, 2022 Report Share Posted October 10, 2022 Add options to a select box in JavaScript: 1) Using the Option constructor and add() method: First, use the Option constructor to create a new option with the specified option text and value: let newOption = new Option('Option Text','Option Value'); Then, call the add() method of the HTMLSelectElement element: const select = document.querySelector('select'); select.add(newOption,undefined); 2) Using the DOM methods First, construct a new option using DOM methods: // create option using DOM const newOption = document.createElement('option'); const optionText = document.createTextNode('Option Text'); // set option text newOption.appendChild(optionText); // and option value newOption.setAttribute('value','Option Value'); Second, add the new option to the select element using the appendChild() method: const select = document.querySelector('select'); select.appendChild(newOption); Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.