SubhanUllah Posted October 10, 2022 Report 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);
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now