HTMLSelectElement: selectedIndex-Eigenschaft
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since Juli 2015.
Die selectedIndex-Eigenschaft des HTMLSelectElement-Interfaces ist der numerische Index des ersten ausgewählten <option>-Elements in einem <select>-Element, falls vorhanden, oder −1, wenn kein <option> ausgewählt ist. Das Setzen dieser Eigenschaft wählt die Option an diesem Index aus und deselektiert alle anderen Optionen, während das Setzen auf -1 alle aktuell ausgewählten Optionen deselektiert.
Wert
Eine Zahl.
Beispiele
>HTML
html
<p id="p">selectedIndex: 0</p>
<select id="select">
<option selected>Option A</option>
<option>Option B</option>
<option>Option C</option>
<option>Option D</option>
<option>Option E</option>
</select>
JavaScript
js
const selectElem = document.getElementById("select");
const pElem = document.getElementById("p");
// When a new <option> is selected
selectElem.addEventListener("change", () => {
const index = selectElem.selectedIndex;
// Add that data to the <p>
pElem.textContent = `selectedIndex: ${index}`;
});
Spezifikationen
| Specification |
|---|
| HTML> # dom-select-selectedindex-dev> |
Browser-Kompatibilität
Loading…