Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

javascript - JavaScript DOM移除元素(JavaScript DOM remove element)

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.

(我正在尝试测试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);
}

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.

(基本上,所有这些代码所做的就是通过单击按钮将iframe注入网页。)

What I would like to happen is if the iframe is already there to delete it.

(我想发生的是,如果iframe已经存在,可以删除它。)

But for some reason I am failing.

(但是由于某种原因,我失败了。)

  ask by Joshua Redfield translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

removeChild should be invoked on the parent, ie:

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

parent.removeChild(child);

In your example, you should be doing something like:

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...