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