我试图测试一个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);
}
检查元素是否存在可以,创建元素也可以,但删除元素就不行了。基本上这段代码的功能是通过点击按钮将一个 iframe 注入到网页中。我希望的是,如果该 iframe 已经存在,则将其删除。但由于某些原因,我失败了。