노드 삭제
함수 | 설명 |
remove() | 노드삭제 |
removeChild(삭제 할 자식 노드) | 자식 노드 삭제 |
예제 ) 하나씩 삭제 | 일괄 삭제 , 전체 체크 | 전체 체크 해제
css↓↓↓
더보기
<style>
table {border-spacing: 0; border-collapse: collapse;}
thead th, tbody td {
border: 1px solid black;
}
</style>
html ↓↓↓
더보기
<button button="type" id="delOne">하나씩 삭제</button>
<button button="type" id="del">일괄 삭제</button>
<table>
<thead>
<th><input type="checkbox" class="allCheck"></th>
<th>번호</th>
<th>이름</th>
<th>내용</th>
<th>날짜</th>
</thead>
<tbody class="table">
<tr>
<td><input type="checkbox" class="check"></td>
<td>1</td>
<td>홍길자</td>
<td>안녕!</td>
<td>2019-01-01</td>
</tr>
<tr>
<td><input type="checkbox" class="check"></td>
<td>2</td>
<td>김길자</td>
<td>안녕!</td>
<td>2019-01-01</td>
</tr>
<tr>
<td><input type="checkbox" class="check"></td>
<td>3</td>
<td>이길자</td>
<td>안녕!</td>
<td>2019-01-01</td>
</tr>
<tr>
<td><input type="checkbox" class="check"></td>
<td>4</td>
<td>고길자</td>
<td>안녕!</td>
<td>2019-01-01</td>
</tr>
</tbody>
script↓↓↓
//하나씩 삭제 removeChild
var delOne = document.getElementById("delOne");
delOne.onclick = function(){
var table = document.querySelector(".table"); //tr의 부모요소
// table.remove(); //한번에 다 삭제됨
// table.removeChild(지울 자식 요소)
console.log(table.children[0]); //배열의 첫번째 요소
table.removeChild(table.firstElementChild); //첫번째 요소
if(table.firstElementChild == null){
alert('삭제할 행이 없습니다.');
}
}
//일괄 삭제 remove
var del = document.getElementById("del");
var check = document.querySelectorAll(".check"); //체크박스 전부
del.onclick = function(){
//this.remove(); //자기 자신을 날림(버튼 삭제)
//console.log(confirm("삭제 할거니")); //컨펌 경고창 (확인, 취소버튼에 따라 return 값이 달라짐 확인: true/취소 :flase)
if(confirm("정말 삭제하시겠습니까?")==false){
return;
}
for(var i = 0; i < check.length; i++){
if(check[i].checked){
check[i].parentElement.parentElement.remove(); //tr삭제
}
}
}
//전체 선택 vs 전체 해제
var allCheck = document.querySelector(".allCheck");
allCheck.onclick = function(){
console.log(allCheck.checked);
if(allCheck.checked){ //전부 체크로 변경
for(var i = 0; i < check.length; i++){
check[i].checked = true;
}
}else{ //전부 체크 해제
for(var i = 0; i < check.length; i++){
check[i].checked = false;
}
}
}
'JavaScript' 카테고리의 다른 글
JS | 클래스 속성 제어하기 (0) | 2023.01.02 |
---|---|
JS | 실습 1 (0) | 2023.01.02 |
JS | 노드 생성, 추가 insertBefore (0) | 2023.01.02 |
JS | 부모 노드, 자식 노드 선택 (0) | 2023.01.02 |
JS | 노드 생성, 추가 (0) | 2022.12.30 |