Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

DOMRectReadOnly.width — rectangle width

The read-only `width` property returns the rectangle’s stored width as a number, preserving its sign and any fractional part.

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

rect.width

DOMRectReadOnly.width is a read-only instance property. Read it as rect.width, without parentheses. It returns a number. The unit depends on the API that supplied the rectangle. For example, for an HTML element, entry.contentRect.width on a ResizeObserverEntry gives the content box width in CSS pixels.

When you construct a rectangle yourself, the third argument to DOMRectReadOnly sets width. A negative width stays negative: with finite coordinates and a negative width, left is x + width and right is x. For the nonnegative horizontal span of a rectangle with finite width, use Math.abs(rect.width).

Assigning to width does not change a DOMRectReadOnly instance: the assignment throws a TypeError in strict mode and is ignored otherwise. If you need a different width, create a new rectangle or use the writable width on a DOMRect. DOMRectReadOnly is a Web API, not part of ECMAScript; check whether your target runtime provides it.

Examples

(() => {
  "use strict";

  // Local fallback for runtimes without the Web API. It models only these three properties.
  function demoReadOnlyRect(x, width) {
    return {
      get width() { return width; },
      get left() { return width < 0 ? x + width : x; },
      get right() { return width < 0 ? x : x + width; },
    };
  }

  const rect = typeof DOMRectReadOnly === "function"
    ? new DOMRectReadOnly(10, 0, -4.5, 3)
    : demoReadOnlyRect(10, -4.5);
  console.log(`width=${rect.width}, left=${rect.left}, right=${rect.right}`);

  try {
    rect.width = 8;
  } catch (error) {
    console.log(`TypeError=${error instanceof TypeError}, width=${rect.width}`);
  }
})();

Result

width=-4.5, left=5.5, right=10
TypeError=true, width=-4.5

Run the code in a browser console that supports `DOMRectReadOnly` to use the native API. If `DOMRectReadOnly` is unavailable, as in Node.js, the example uses a local fallback that models only `width`, `left`, and `right`. The negative width stays `-4.5`, and the strict-mode assignment throws a `TypeError` that the example catches.

Related lessons

  • JavaScript · Lesson 32 · Intermediate · Version: 3

Sources