문제

바디 태그 이외의 부모가없는 DOM 요소를 제거 할 수 있습니까? 나는 이것이 jQuery와 같은 프레임 워크에서 쉽다는 것을 알고 있지만, 직선 JavaScript를 고수하려고합니다.

그렇지 않으면 내가 찾은 코드는 다음과 같습니다.

function removeElement(parentDiv, childDiv){
     if (childDiv == parentDiv) {
          alert("The parent div cannot be removed.");
     }
     else if (document.getElementById(childDiv)) {     
          var child = document.getElementById(childDiv);
          var parent = document.getElementById(parentDiv);
          parent.removeChild(child);
     }
     else {
          alert("Child div has already been removed or does not exist.");
          return false;
     }
}   

감사!

도움이 되었습니까?

해결책

요소의 부모를 얻은 다음 요소를 제거 할 수 있어야합니다.

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

업데이트

이것을 htmlelement의 새로운 방법으로 설정할 수 있습니다.

HTMLElement.prototype.remove = function() { this.parentNode.removeChild(this); return this; }

그리고 그렇게합니다 el.remove() (요소도 반환 할 것입니다)

다른 팁

childDiv.remove();

Chrome 25.0.1364.155에서 작동합니다

이것은 IE11 또는 Opera Mini에서는 작동하지 않지만 다른 모든 브라우저에서 지원됩니다.

여기를 봐: Caniuse의 Childnode-remove에 대한 참조

나는 당신이 같은 일을 할 수 있다고 생각합니다 ...

var child = document.getElementById(childDiv);
//var parent = document.getElementById(parentDiv);
child.parentNode.removeChild(child);

보다 node.parentNode 그것에 대한 자세한 내용은.

document.body.removeChild(child);

사용 요소 제거 outerHTML 재산

remElement(document.getElementById('title'));
remElement(document.getElementById('alpha'));

function remElement(obj) {
obj.outerHTML="";
}

이 기능은 ID를 사용하여 요소를 간단히 제거합니다.

function removeElement (id) { 
  document.getElementById(id).parentElement.removeChild(document.getElementById(id));
}

좋아, 당신은 기본적으로 DOM에서 dom 요소를 삭제하기 위해 부모를 알 필요가 없습니다. 아래 코드를보십시오. JavaScript에서 노드 요소를 삭제하는 순서는 다음과 같습니다.

Element + parentNode + removeChild(Element);

보시다시피 요소를 먼저 찾은 다음 .parentNode를 사용한 다음 요소 인 어린이를 다시 제거하므로 부모를 전혀 알 필요가 없습니다!

이제 실제 코드를보십시오.

var navigation = document.getElementById('navigation');
if(navigation) {
  navigation.parentNode.removeChild(navigation);
}

또는 함수로

function removeNode(element) {
  if(element) { //check if it's not null
    element.parentNode.removeChild(element);
  } 
} //call it like : removeNode(document.getElementById('navigation'));

또한 jQuery는 다음과 같이 널리 사용되는 remove () 함수가 있습니다.

$('#navigation').remove();

또한 네이티브가 있습니다 ChildNode.remove() IE 및 기존 브라우저는 아니지만 Polyfill을 할 수 있으며 MDN의 제안 된 폴리 필을 볼 수 있습니다.

폴리 필
Internet Explorer 9에서 remove () 메소드를 다음 코드로 폴리 핑 할 수 있습니다.

//from:https://github.com/jserz/js_piece/blob/master/DOM/ChildNode/remove()/remove().md
(function (arr) {
  arr.forEach(function (item) {
    if (item.hasOwnProperty('remove')) {
      return;
    }
    Object.defineProperty(item, 'remove', {
      configurable: true,
      enumerable: true,
      writable: true,
      value: function remove() {
        this.parentNode.removeChild(this);
      }
    });
  });
})([Element.prototype, CharacterData.prototype, DocumentType.prototype]);

그것에 대해 더 배우고 싶다면 이것을 방문하십시오. 링크 MDN에서.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top