Home > Web Front-end > JS Tutorial > body text

How to Properly Remove DOM Elements in JavaScript?

Barbara Streisand
Release: 2024-10-31 20:38:29
Original
759 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!