HTML DOM의 select length 속성은 HTML 문서에서 드롭다운 목록(select) 내부에 포함된 <option> 요소의 총 개수를 반환하는 속성입니다. 자바스크립트를 사용해 특정 select 요소가 몇 개의 옵션을 가지고 있는지 손쉽게 확인할 수 있습니다.
구문(Syntax)
length 속성의 기본적인 사용 구문은 다음과 같습니다.
object.length
예제(Example)
이제 실제 코드를 통해 select length 속성을 어떻게 활용하는지 살펴보겠습니다. 아래 예제는 버튼을 클릭하면 드롭다운 목록에 포함된 과목 옵션의 개수를 화면에 표시합니다.
<!DOCTYPE html>
<html>
<head>
<style>
html{
height:100%;
}
body{
text-align:center;
color:#fff;
background: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%) center/cover no-repeat;
height:100%;
}
p{
font-weight:700;
font-size:1.2rem;
}
.drop-down{
width:35%;
border:2px solid #fff;
font-weight:bold;
padding:8px;
}
.btn{
background:#0197F6;
border:none;
height:2rem;
border-radius:2px;
width:35%;
margin:2rem auto;
display:block;
color:#fff;
outline:none;
cursor:pointer;
}
.show{
font-size:1.5rem;
font-weight:bold;
}
</style>
</head>
<body>
<h1>DOM Select length Property Demo</h1>
<p>안녕하세요! 좋아하는 과목을 선택하세요:</p>
<select class='drop-down'>
<option>Physics(물리)</option>
<option>Maths(수학)</option>
<option>Chemistry(화학)</option>
<option>English(영어)</option>
</select>
<button onclick="showLength()" class="btn">옵션 개수 확인하기</button>
<div class="show"></div>
<script>
function showLength() {
var dropDown = document.querySelector(".drop-down");
var showMsg = document.querySelector(".show");
showMsg.innerHTML ="옵션 개수: " + dropDown.length;
}
</script>
</body>
</html>
코드 설명
위 예제의 핵심 로직은 다음과 같습니다.
document.querySelector(".drop-down"): 클래스명이 drop-down인 select 요소를 가져옵니다.dropDown.length: 해당 select 요소 안에 있는<option>요소의 개수를 반환합니다.showMsg.innerHTML: 반환된 값을 화면의 div 영역에 출력하여 사용자에게 보여줍니다.
실행 결과(Output)
위 코드를 실행하면 다음과 같은 화면이 나타납니다.

이제 "옵션 개수 확인하기" 버튼을 클릭해 보세요. 그러면 드롭다운 목록에 포함된 옵션의 개수가 즉시 표시됩니다.

버튼을 클릭하면 "옵션 개수: 4"라는 결과가 출력되는데, 이는 드롭다운 목록에 물리, 수학, 화학, 영어 총 4개의 <option> 요소가 존재하기 때문입니다.
정리
HTML DOM의 select length 속성은 별도의 반복문 없이도 드롭다운 목록의 옵션 개수를 한 번에 파악할 수 있는 간편한 방법입니다. 폼 유효성 검사나 동적으로 옵션을 추가·삭제할 때 현재 옵션 수를 확인하는 용도로 유용하게 활용할 수 있습니다.