JavaScript로 드롭다운 목록의 모든 옵션 표시하기
드롭다운 목록(<select>)에 포함된 모든 옵션을 표시하려면 options 속성을 사용하면 됩니다. HTMLSelectElement 객체가 제공하는 options 컬렉션에는 목록 안의 모든 <option> 요소가 담겨 있으며, 여기에 length 속성을 함께 활용하면 옵션의 개수만큼 반복 처리하여 전체 항목을 손쉽게 가져올 수 있습니다.
각 옵션의 텍스트 값은 options[i].text 형태로 접근할 수 있고, 필요에 따라 value, index, selected 같은 속성도 함께 확인할 수 있습니다.
예제
아래 예제 코드를 실행하고 버튼을 클릭하면 드롭다운 목록의 모든 옵션이 화면에 출력됩니다.
<!DOCTYPE html>
<html>
<body>
<form id="myForm">
<select id="selectNow">
<option>One</option>
<option>Two</option>
<option>Three</option>
</select>
<input type="button" onclick="display()" value="Click">
</form>
<p>Click the button to get all the options</p>
<script>
function display() {
var a, i, options;
a = document.getElementById("selectNow");
options = "";
for (i = 0; i < a.length; i++) {
options = options + "<br> " + a.options[i].text;
}
document.write("DropDown Options: "+options);
}
</script>
</body>
</html>코드 설명
document.getElementById("selectNow")를 통해 select 요소의 참조를 얻어옵니다.a.length로 드롭다운에 포함된 옵션의 총 개수를 구한 뒤, 그만큼 for문을 반복합니다.a.options[i].text로 각 옵션의 텍스트 값을 하나씩 읽어 문자열로 누적합니다.- 버튼 클릭 시
display()함수가 실행되어 모든 옵션이 화면에 표시됩니다.
이처럼 options 속성과 length 속성만 활용하면 별도의 라이브러리 없이도 순수 JavaScript만으로 드롭다운 목록의 전체 옵션을 간단하게 다룰 수 있습니다.