Study/JavaScript
[JS] closest & parentElement
taecongs
2023. 7. 26. 16:00

알고있으면 좋은 Javascript Tip✨
closest()
- 현재 기준의 Element에서 파라미터에 입력된 선택자에 만족할 때까지 탐색한다.
- 이 중, 가장 가까운 선택자를 선택해 가져온다.
- 조건에 만족하는 요소가 없을 경우에는 Null을 반환한다.
const $selectId = Number($selectIcon.closest('.floor-row').dataset.floorId);
- .icon 을 클릭하면 .icon의 부모 요소를 하나씩 찾아서 올라간다.
- .floor-row라는 부모 요소(클래스)를 찾을 때까지 올라간다.
parentElement()
- 부모 요소를 한 단계 씩 찾아서 올라간다.
const $selectId = Number($selectIcon.parentElement.parentElement.parentElement.dataset.floorId);
