Program Club

JavaScript를 사용하여 HTML에서 자식 노드를 제거하려면 어떻게해야합니까?

proclub 2020. 11. 3. 19:28
반응형

JavaScript를 사용하여 HTML에서 자식 노드를 제거하려면 어떻게해야합니까?


같은 기능이 document.getElementById("FirstDiv").clear()있습니까?


원래 질문에 답하려면 다양한 방법이 있지만 다음이 가장 간단합니다.

제거하려는 자식 노드에 대한 핸들이 이미있는 경우, 즉 참조를 보유하는 JavaScript 변수가있는 경우 :

myChildNode.parentNode.removeChild(myChildNode);

이미이 작업을 수행하는 수많은 라이브러리 중 하나를 사용하지 않는 경우이를 추상화하는 함수를 만들고 싶을 것입니다.

function removeElement(node) {
    node.parentNode.removeChild(node);
}

편집 : 다른 사람들이 언급했듯이 : 제거하려는 노드에 연결된 이벤트 처리기가있는 경우 제거되는 노드에 대한 마지막 참조가 범위를 벗어나기 전에 이러한 처리기를 연결 해제하여 잘못된 구현을 방지해야합니다. JavaScript 인터프리터 누수 메모리의.


div를 지우고 모든 자식 노드를 제거하려면 다음을 넣을 수 있습니다.

var mydiv = document.getElementById('FirstDiv');
while(mydiv.firstChild) {
  mydiv.removeChild(mydiv.firstChild);
}

targetNode.remove ()

이 늦은 2015 년 W3C에서 권장하고있다 바닐라 JS는 . 이전 방법보다 훨씬 좋고 / 깨끗합니다.

사용 사례 :

document.getElementById("FirstDiv").remove();

이전 버전과의 호환성을 보장하기 위해 폴리 필이 필요한 경우 :

if (!('remove' in Element.prototype)) {
    Element.prototype.remove = function() {
        if (this.parentNode) {
            this.parentNode.removeChild(this);
        }
    };
}

Mozilla 문서

지원되는 브라우저 -92 % 2018 년 3 월


IE에서 메모리 누수를 방지하려면 노드를 제거하기 전에 노드에 설정 한 이벤트 처리기를 제거해야합니다.


jQuery 솔루션

HTML

<select id="foo">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>

자바 스크립트

// remove child "option" element with a "value" attribute equal to "2"
$("#foo > option[value='2']").remove();

// remove all child "option" elements
$("#foo > option").remove();

참조 :

속성 같음 선택기 [이름 = 값]

특정 값과 정확히 같은 값을 가진 지정된 속성이있는 요소를 선택합니다.

자식 선택기 ( "부모> 자식")

"부모"로 지정된 요소의 "하위"로 지정된 모든 직접 하위 요소를 선택합니다.

.풀다()

Similar to .empty(), the .remove() method takes elements out of the DOM. We use .remove() when we want to remove the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed.


Use the following code:

//for Internet Explorer
document.getElementById("FirstDiv").removeNode(true);

//for other browsers
var fDiv = document.getElementById("FirstDiv");
fDiv.removeChild(fDiv.childNodes[0]); //first check on which node your required node exists, if it is on [0] use this, otherwise use where it exists.

    var p=document.getElementById('childId').parentNode;
    var c=document.getElementById('childId');
    p.removeChild(c);
    alert('Deleted');

p is parent node and c is child node
parentNode is a JavaScript variable which contains parent reference

Easy to understand


You should be able to use the .RemoveNode method of the node or the .RemoveChild method of the parent node.


You should probably use a JavaScript library to do things like this.

For example, MochiKit has a function removeElement, and jQuery has remove.

참고 URL : https://stackoverflow.com/questions/13763/how-can-i-remove-a-child-node-in-html-using-javascript

반응형