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.

2

1 Answer 1

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);

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.