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をWebページに挿入することです。削除したいiframeがすでに存在する場合、私が実行したいことです。しかし、何らかの理由で失敗しています。