Keywords: JavaScript | DOM Manipulation | Dropdown Menu
Abstract: This article provides an in-depth exploration of methods for retrieving the currently displayed text from dropdown menus (select elements) in JavaScript. By analyzing DOM structure and the selectedIndex property, it details how to use the options collection and text property to accurately obtain user-visible option text, rather than just the value attribute. The article includes comprehensive code examples and DOM manipulation principles to help developers deeply understand form element handling mechanisms in browsers.
DOM Structure Analysis of Dropdown Menus
In web development, dropdown menus are typically implemented using the <select> element, which contains multiple <option> child elements. Each option has two important attributes: value and display text. Understanding this structure is crucial for properly manipulating dropdown menus.
Core Method for Retrieving Display Text
To obtain the text of the currently selected option, you need to access the options collection and selectedIndex property of the <select> element. The specific implementation code is as follows:
var selectElement = document.getElementById("newSkill");
var displayedText = selectElement.options[selectElement.selectedIndex].text;
Method Principle Explanation
The selectedIndex property returns the index position of the currently selected option in the options collection, starting from 0. By accessing the corresponding option element through this index and then using the text property, you can obtain the user-visible display text. This method contrasts with directly retrieving the value attribute, which returns the option's value rather than its display content.
Complete Example and Comparison
Consider the following HTML structure:
<select name="newSkill" id="newSkill">
<option value="1">Programming Skill</option>
<option value="2">Design Ability</option>
<option value="3">Communication Skill</option>
</select>
When the user selects "Design Ability":
// Get value attribute
var value = document.getElementById("newSkill").value; // Returns "2"
// Get display text
var select = document.getElementById("newSkill");
var text = select.options[select.selectedIndex].text; // Returns "Design Ability"
Browser Compatibility and Best Practices
This method is well-supported across all modern browsers. In practical development, it's recommended to always check if selectedIndex is -1 (indicating no option is selected) to avoid potential errors. For dynamically updated dropdown menus, ensure to re-retrieve the display text after option changes.