create element option code example

Example: javascript add option element to select

javascript add option/element to select:
const newOpt = document.getElementById('option-input');
let mySelect = document.getElementById('mySelect'); //Object not array
const opts = Object.values(mySelect.options);
const option = document.createElement('option');
optValues = opts.map(opt => opt.value.toLowerCase());
//Validate if option exists
if(optValues.indexOf(newOpt.value.toLowerCase()) !== -1){
  	newOpt.nextElementSibling.after("Category exists");
   }else{
   option.value = newOpt.value;
    option.text = newOpt.value;
    mySelect.add(option);
    mySelect.value = option.value;
   }

Tags:

Html Example