gpt4 book ai didi

JavaScript DOM 移除元素

转载 作者:IT老高 更新时间:2023-10-28 13:15:43 26 4
gpt4 key购买 nike

我正在尝试测试一个 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 注入(inject)网页。我想要发生的是如果 iframe 已经在那里删除它。但由于某种原因,我失败了。

最佳答案

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

parent.removeChild(child);

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

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

关于JavaScript DOM 移除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8830839/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com