小编Jos*_*eld的帖子

JavaScript DOM删除元素

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

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);
}
Run Code Online (Sandbox Code Playgroud)

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

javascript dom

183
推荐指数
4
解决办法
30万
查看次数

标签 统计

dom ×1

javascript ×1