본문 바로가기
오류 처리

remove child 오류

by dal_been 2023. 2. 23.
728x90

uncaught type error: cannot read property 'removeChild' of 'null' error

라는 오류가 자주 나왔음 

  <script>
            function show(){
                let newItem=document.createElement('li');
                let text=document.querySelector('#subject');
                newItem.innerHTML=text.value;

                let item=document.getElementById('itemlist');
                item.appendChild(newItem);

                text.value="";

                let liList = document.querySelectorAll('li');
                for(let i=0; i<liList.length; i++){
                liList[i].addEventListener("click", function (){
                   
                 this.parentNode.removeChild(this);
                });
            }

            //if를 안붙이면 liList의 click이LOOP에 빠짐-->에러뜸

        }

        function enterkey() {
	        if (window.event.keyCode == 13) {
    	    // 엔터키가 눌렸을 때
            }      
        }
   </script>

실행은 되지만 왜 에러?? 

알아본 결과.. 추측하자면 li를 붙일 때마다 li를 제거하는 이벤트도 계속 호출되는 거임 => 루프가 생긴다??

클릭하여 삭제하면 에러가 뜨는데 이유는 이미존재하지 않아서..

 

그냥 li만들때마다 li 제거 이벤트도 계속 생성되서 라고 생각하면 될듯..

 

        <script>
            
            function show(){
                let newItem=document.createElement('li');
                let text=document.querySelector('#subject');
                newItem.innerHTML=text.value;

                let item=document.getElementById('itemlist');
                item.appendChild(newItem);

                text.value="";

                let liList = document.querySelectorAll('li');
                for(let i=0; i<liList.length; i++){
                liList[i].addEventListener("click", function (){
                    if(this.parentNode)
                 this.parentNode.removeChild(this);
                });
            }

            //if를 안붙이면 liList의 click이LOOP에 빠짐-->에러뜸

        }

        function enterkey() {
	        if (window.event.keyCode == 13) {
    	    // 엔터키가 눌렸을 때
            }      
        }   



          
        </script>

 

if(this.parentNode)를 붙여서 부모요소가 있으면 호출한다로 제약걸기

--->오류 사라짐