[Javascript] select option text, value, 속성 값 가져오기

김승훈·2020년 4월 17일
3

퍼블리싱

목록 보기
2/2
<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <select class="animal">
    <option data-title="data-cat" value="cat" selected>고양이</option>
    <option data-title="data-dog" value="dog">강아지</option>
    <option data-title="data-pig" value="pig">돼지</option>
  </select>
</body>
<script>
  let animalSelect = document.querySelector('.animal');
  let selectEvent = function(){
    let text = animalSelect.options[animalSelect.selectedIndex].text; //고양이 
    let value = animalSelect.options[animalSelect.selectedIndex].value; // cat 
    let dataTitle = animalSelect.options[animalSelect.selectedIndex].getAttribute('data-title') // data-cat
    console.log(text);
    console.log(value);
    console.log(dataTitle);
  }
  
  animalSelect.addEventListener("change", selectEvent);
 
</script>
</html>
selectObject.selectedIndex // index 가져오기 

let text = animalSelect.options[animalSelect.selectedIndex].text; 
//텍스트 가져오기
let value = animalSelect.options[animalSelect.selectedIndex].value;
// 값 가져오기
let dataTitle = animalSelect.options[animalSelect.selectedIndex].getAttribute('data-title'); 
//속성 값 가져오기

너무 제이쿼리에 익숙해져버린 것 같다.. 바닐라 공부 ~

0개의 댓글