Check if a given DOMRect is contained within another DOMRect

True when the target lies inside the container or on its edges.

JavaScript Version 1.0.0 · MIT · .md

check-if-a-given-dom-rect-is-contained-within-another-dom-rect.js
function isContained({ target, container }) { return target.x >= container.x && target.x + target.width <= container.x + container.width && target.y >= container.y && target.y + target.height <= container.y + container.height; }

Input & expected output

Input

{
  "target": {
    "x": 10,
    "y": 10,
    "width": 20,
    "height": 20
  },
  "container": {
    "x": 0,
    "y": 0,
    "width": 40,
    "height": 40
  }
}

Expected output

true

The edge case

Input

{
  "target": {
    "x": 30,
    "y": 10,
    "width": 20,
    "height": 20
  },
  "container": {
    "x": 0,
    "y": 0,
    "width": 40,
    "height": 40
  }
}

Expected output

false

Know the limits

  • Pass rects from getBoundingClientRect() or plain { x, y, width, height } objects. The original read left and top, which plain objects lack.
  • Assumes non-negative width and height, as getBoundingClientRect() returns. Shared edges count as contained.

The function above is the implementation used by the lab. The lab validates JSON types and caps size before execution; include equivalent validation when accepting untrusted input in your application.

Source & maintenance

Based on Check if a given DOMRect is contained within another DOMRect from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.

Reads x and y, which DOMRects and plain JSON rects share, instead of left and top; runs in the lab. Original MDX retained as inert source evidence.

Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.

Local fixture scope · Node.js 22.23.2 · reviewed October 28, 2026. No external service is required.

Keep exploring

Type two or more characters. Try “duplicate”, “webhook” or “retry”.