0

I want to add a <select> element using javascript. I also want in the same function to add both a class, an id and 3 <option> elements with values 1-3.

I know this seemes like a lot, but hope some of you have something that will help me.

  • 1
    What have you tried, it shouldn't be to hard [to figure out](http://stackoverflow.com/questions/17001961/javascript-add-select-programmatically) ! – adeneo Oct 27 '16 at 16:57
  • Google search used to find the duplicate: [site:stackoverflow.com javascript how to create select with options](https://www.google.com/search?q=site%3Astackoverflow.com+javascript+how+to+create+select+with+options) –  Oct 27 '16 at 17:02

1 Answers1

0

While you could just as well do this in HTML straight away, here you go:

const $select = document.createElement('select');
const numberOfOptions = 3;

$select.classList.add('my-select');
$select.id = 'my-select';

const createOption = value => {
  const $option = document.createElement('option');
  
  $option.textContent = value;
  $option.value = value;
  
  return $option;
};

for (let i = 0; i < numberOfOptions; ++i) {
  const value = i + 1;
  const $option = createOption(value);
  $select.appendChild($option);
}

document.body.appendChild($select);
jdlm
  • 6,327
  • 5
  • 29
  • 49