質問
bodyタグ以外に親を持たない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));
}
OK、基本的に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();
IEおよび古いブラウザにはないネイティブの ChildNode.remove()
もありますが、ポリフィルできます。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のリンク。