Try adding the <div>
in HTML instead of creating it everytime or you'll need to remove each one when a change event happens. When an element is removed or added to and from the DOM a reflow happens. A relow causes a broswer to recalculate position and distance of all content within the page. Changing an element that already exists on the page is less costly to browser processing. See this question on reflows and repaints. The example is a modified version of OP.
Do not use onevent attributes. Inline event handlers are garbage, so it's replaced by a onevent property handler, an .addEventListener()
would be a better choice as well.
The event.target
Event Object property is used to point to the changed element (ie .select
), this
would also work. No need to do a document.querySelector()
inside of function.
Added selected
and disabled
to first <option>
popup as an actual value.
To get the current value of a <select>
.value
property will suffice.
The <div>
is referenced with .nextElementSibling
of .select
and the text is overwritten by .textContent
property.
Use .selectedIndex = "0";
to reset .select
instead of .value=""
.
As per Oskar Grosser's comments below.
document.querySelector(".select").onchange = dropdown;
function dropdown(e) {
const sel = event.target;
let selected = sel.value;
const div = sel.nextElementSibling;
div.textContent = selected;
sel.selectedIndex = "0";
}
<select class="select">
<option selected disabled>choose</option>
<option value="op1">Option 1</option>
<option value="op2">Option 2</option>
</select>
<div></div>