Home  >  Article  >  Web Front-end  >  Why Does My JavaScript DOM Element Removal Fail, Even Though I\'m Checking for Its Existence?

Why Does My JavaScript DOM Element Removal Fail, Even Though I\'m Checking for Its Existence?

Linda Hamilton
Linda HamiltonOriginal
2024-11-01 03:36:28663browse

Why Does My JavaScript DOM Element Removal Fail, Even Though I'm Checking for Its Existence?

JavaScript DOM Element Removal

In this code snippet, the author attempts to check if a DOM element called "injected_frame" exists. If it does, they want to remove it; otherwise, they want to create and inject it. While the creation and detection work as expected, the element removal fails.

The Solution

The issue lies in the removal method invocation. The removeChild method should be invoked on the parent element, not the child. In this case, the correct code is:

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

By invoking removeChild on the parent, you effectively remove the "injected_frame" element from the DOM.

The above is the detailed content of Why Does My JavaScript DOM Element Removal Fail, Even Though I\'m Checking for Its Existence?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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