Home > Article > Web Front-end > How to Properly Remove DOM Elements in JavaScript?
JavaScript DOM - Removing Elements
In JavaScript, when working with the Document Object Model (DOM), removing elements is a common task. When an existing element needs to be removed from the DOM, the removeChild method is employed.
One common scenario is to test for the existence of an element and either delete it if present or create it if absent. This approach ensures that the element is only created if it doesn't already exist.
Consider the following code:
<code class="javascript">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); }</code>
In this code, checking for the existence of the iframe and creating it if absent works as intended. However, the attempt to remove the iframe using iframe.removeChild(frameid.childNodes[0]) fails.
The error lies in the use of iframe.removeChild. The removeChild method should be called on the parent of the element that is being removed. In this case, the parent of frameid is the body element. Therefore, the correct removal method is:
<code class="javascript">if (frameid) { frameid.parentNode.removeChild(frameid); }</code>
The above is the detailed content of How to Properly Remove DOM Elements in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!