DEV Community

Cover image for Dynamically create option in select element
Jharna Khatun
Jharna Khatun

Posted on

Dynamically create option in select element

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);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)