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

How to Detect Element Addition in the DOM: Deprecation and Alternatives?

Susan Sarandon
Release: 2024-10-21 08:47:29
Original
418 people have browsed it

How to Detect Element Addition in the DOM: Deprecation and Alternatives?

Observing Element Addition in the DOM

To receive a notification when an element is added to a webpage, a few approaches are available:

Deprecated Mutation Events:

Previously, mutation events (e.g., DOMNodeInserted) could be used to monitor DOM changes. However, these events are now deprecated.

Continuous Polling:

An outdated approach involves using setInterval() to regularly check for the presence of the desired element:

<code class="js">function checkDOMChange() {
  // Check for element presence...

  // Continue polling after 100 milliseconds
  setTimeout(checkDOMChange, 100);
}</code>
Copy after login

This is an inefficient solution that consumes significant CPU resources.

Recommended: MutationObserver

Modern browsers support MutationObserver, which provides an alternative to mutation events. It allows you to observe DOM changes and execute a callback function when an element is added:

<code class="js">const observer = new MutationObserver(mutations => {
  // Process DOM changes...
});

observer.observe(document.documentElement, { childList: true });</code>
Copy after login

By implementing MutationObserver, you can effectively monitor DOM additions without the limitations of deprecated mutation events or the inefficiency of continuous polling.

The above is the detailed content of How to Detect Element Addition in the DOM: Deprecation and Alternatives?. For more information, please follow other related articles on the PHP Chinese website!

source:php
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!