JavaScript DOM 移除元素 [英] JavaScript DOM remove element

查看:24
本文介绍了JavaScript DOM 移除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试测试 DOM 元素是否存在,如果存在则删除它,如果不存在则创建它.

I'm trying to test if a DOM element exists, and if it does exist delete it, and if it doesn't exist create it.

var duskdawnkey = localStorage["duskdawnkey"];
var iframe = document.createElement("iframe");
var whereto = document.getElementById("debug");
var frameid = document.getElementById("injected_frame");
iframe.setAttribute("id", "injected_frame");
iframe.setAttribute("src", 'http://google.com');
iframe.setAttribute("width", "100%");
iframe.setAttribute("height", "400");

if (frameid) // check and see if iframe is already on page
{ //yes? Remove iframe
    iframe.removeChild(frameid.childNodes[0]);
} else // no? Inject iframe
{
    whereto.appendChild(iframe);
    // add the newly created element and it's content into the DOM
    my_div = document.getElementById("debug");
    document.body.insertBefore(iframe, my_div);
}

检查它是否存在有效,创建元素有效,但删除元素无效.基本上所有这些代码都是通过单击按钮将 iframe 注入网页.我想要发生的是,如果 iframe 已经存在以将其删除.但由于某种原因,我失败了.

Checking if it exists works, creating the element works, but deleting the element doesn't. Basically all this code does is inject an iframe into a webpage by clicking a button. What I would like to happen is if the iframe is already there to delete it. But for some reason I am failing.

推荐答案

removeChild 应该在父级上调用,即:

removeChild should be invoked on the parent, i.e.:

parent.removeChild(child);

在您的示例中,您应该执行以下操作:

In your example, you should be doing something like:

if (frameid) {
    frameid.parentNode.removeChild(frameid);
}

这篇关于JavaScript DOM 移除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆