Node.prototype.contains() Polyfill

1.0.0 · abandoned · verified Sun Apr 19

The `node-contains` package, currently at version 1.0.0 and last published in September 2014, was designed to provide a cross-browser polyfill for the `Node.prototype.contains()` DOM method. Its original purpose was to ensure consistent behavior across older web browsers that lacked native support for this functionality. However, this method has been natively supported by all major web browsers since July 2015. Consequently, this package is now largely obsolete and considered abandoned for modern web development. While it might still be encountered in projects targeting extremely legacy environments, for any contemporary application, including `node-contains` introduces unnecessary overhead and potential compatibility issues. It does not follow a regular release cadence and offers no unique differentiators over native browser implementations.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to include the `node-contains` polyfill and then use the `Node.prototype.contains()` method to check if a DOM node is a descendant of another.

import 'node-contains'; // Apply the polyfill (though likely unnecessary in modern browsers)

function checkContains() {
  const parentDiv = document.createElement('div');
  parentDiv.id = 'parent';
  const childSpan = document.createElement('span');
  childSpan.id = 'child';
  parentDiv.appendChild(childSpan);

  document.body.appendChild(parentDiv);

  // Using Node.prototype.contains() after the polyfill (or native support)
  const isContained = parentDiv.contains(childSpan);
  const selfContained = parentDiv.contains(parentDiv); // Node is considered to contain itself
  const notContained = document.body.contains(document.createElement('p'));

  console.log('Is childSpan contained in parentDiv?', isContained); // Expected: true
  console.log('Is parentDiv contained in itself?', selfContained); // Expected: true
  console.log('Is new P not contained in body?', notContained); // Expected: false (unless appended)

  document.body.removeChild(parentDiv);
}

// Run the check when the DOM is ready
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', checkContains);
} else {
  checkContains();
}

view raw JSON →