상세 컨텐츠

본문 제목

[ JavaScript ] function - 목록 안의 요소들 없애기

FrontEnd/JavaScript

by SangHoonE 2021. 12. 20. 15:52

본문

반응형

 

Javascript로 select box 내의 option들을 특정 조건에 의해 함수를 호출하여 제거하려고 한다. 
검색 기능으로 사용하면 유용하다.

 

물론 select box 말고도 p, span, div...등등 부모-자식 관계의 태그들이라면 모두 가능하다.

 

Node . removeChild 를 사용한다.

const item_name = document.querySelector('#item_name')	// item_name이라는 부모 요소
while (item_name.firstChild) {		// 첫번째 자식 태그가 존재하면 무한 반복
      item_name.removeChild(item_name.firstChild);		// 첫번째 자식 태그를 제거한다. 
 }

 

item_name 이라는 id를 가진 태그를 querySelector로 가져온다.

가져온 태그 내 자식 태그가 1개 이상일 때 반복문이 실행된다.

그리고 removeChild를 통해 자식요소를 제거한다.

 

 

 

Node.removeChild() - Web APIs | MDN

The removeChild() method of the Node interface removes a child node from the DOM and returns the removed node.

developer.mozilla.org

 

관련글 더보기

댓글 영역