📜  HTML | DOM Select selectedIndex 属性(1)

📅  最后修改于: 2023-12-03 14:41:48.675000             🧑  作者: Mango

HTML | DOM Select selectedIndex 属性

The selectedIndex property of the HTML DOM Select element is used to get or set the index of the currently selected option in a dropdown list. This property allows you to programmatically manipulate the selection of options in a select element.

Getting the selectedIndex

To get the index of the currently selected option, use the selectedIndex property of the select element. The index is a zero-based integer, where the first option has an index of 0, the second option has an index of 1, and so on.

const selectElement = document.querySelector('#mySelect');
const selectedIndex = selectElement.selectedIndex;
console.log(selectedIndex); // Output: 2

In the above example, the selectedIndex property is used to retrieve the index of the selected option in the select element with the id mySelect.

Setting the selectedIndex

To set the selected option in a dropdown list programmatically, you can modify the selectedIndex property of the select element. By assigning a new index value to this property, you can change the selection.

const selectElement = document.querySelector('#mySelect');
selectElement.selectedIndex = 1;

In the above example, the selectedIndex property is set to 1, which will make the second option as the selected option in the select element with the id mySelect.

Limitations and Considerations

It is important to note that changing the selectedIndex property does not trigger the change event of the select element. If you want to perform additional actions when the selection changes, you need to manually handle the change event.

Also, if no option is selected, the value of the selectedIndex property will be -1.

Conclusion

The selectedIndex property of the HTML DOM Select element allows you to manage the selected option in a dropdown list programmatically. Whether you want to retrieve the currently selected option or set a new selection, this property provides a convenient way to work with select elements in JavaScript.

Remember to refer to the official documentation for more detailed information: