getElementsByStyleLoading saved progress…

getElementsByStyle

Write a function that searches a DOM subtree and returns every descendant element whose inline style sets a given CSS property to a given value. For example, getElementsByStyle(root, 'display', 'none') finds all elements hidden via a style="display: none" attribute. It's a traversal exercise with a twist: you match against the element's own inline style, parsed correctly, not by string-searching the raw attribute.

Signature

function getElementsByStyle(
  root: Element,
  property: string, // a CSS property name, e.g. 'display'
  value: string,    // the value to match, e.g. 'none'
): Element[];

Returns a plain array of matching descendants, in document order.

Examples

const root = document.createElement('div');
root.innerHTML =
  '<p style="display: none">a</p>' +
  '<div><span style="display: none">b</span></div>';

getElementsByStyle(root, 'display', 'none');
// → [<p>a</p>, <span>b</span>]   (both, including the nested one, in order)
root.innerHTML =
  '<p style="display: none">a</p>' +
  '<p style="display: block">b</p>';

getElementsByStyle(root, 'display', 'none'); // → [<p>a</p>]  (only the exact value)
getElementsByStyle(root, 'color', 'red');    // → []          (no element sets it)

Notes

  • Inline styles only. You match against each element's own style attribute (its el.style), not its computed or cascaded style. An element styled by a stylesheet rule does not count.
  • Descendants only. The root itself is never included, even if its inline style matches.
  • Every depth. Matches can be nested arbitrarily deep — search the whole subtree, not just direct children.
  • Document order. Return matches in the order they appear in the document (a pre-order traversal).
  • Exact value. value must match the property's parsed inline value exactly. Searching 'none' must not match 'none-ish' or a different property that happens to share the value.
  • Elements only. Skip text and comment nodes — return only element nodes.
Loading editor…