Dynamically create option in select element
Jharna Khatun
Posted on October 20, 2024
There are two ways to create an option dynamically :
1) Using the Option constructor and add() method
2) Using the DOM methods
1) Using the Option constructor and add() method :
let newOption = new Option('Option Text','Option Value');
const select = document.querySelector('select');
select.add(newOption,undefined);
2) Using the 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');
const select = document.querySelector('select');
select.appendChild(newOption);
π πͺ π
π©
Jharna Khatun
Posted on October 20, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
webdev Create a Stunning 3D Bend & Reveal Hover Effect with Illusionistic Background Using HTML & CSS
November 27, 2024