Find elements whose computed styles match given CSS values
A design-system team is auditing a product page. They want a console helper that lists every element that actually renders with a given look, for example “everything that ends up red and italic”, no matter whether the style comes from an inline style attribute, a stylesheet class, the browser’s default styles, or is inherited from a parent.
Implement findByComputedStyle(root, styles). It returns every element inside root whose computed style matches all the given properties.
findByComputedStyle(root, styles) // => Element[]
root is an element attached to the document.styles is an object that maps CSS property names to values, for example { color: 'red', fontStyle: 'italic' }. Names can be camelCase (fontWeight) or kebab-case ('font-weight'). Values are strings or numbers.styles, its computed value (from getComputedStyle) equals the requested value.'red', '#f00' and 'rgb(255, 0, 0)' all request the same color, and 'bold' requests the same weight as '700'. Convert each requested value to its computed form before comparing.{ color: 'banana' }), nothing matches: return [].styles object matches every element.root only, not root itself. Return them in document order, as a new array.em or % are not tested.// <style> .warning { font-weight: bold; } </style>
const panel = document.createElement('div');
panel.innerHTML = `
<p style="color: red">Out of stock</p>
<p class="warning" style="color: #ff0000">Only <em>2</em> left</p>
<p style="color: blue">In stock</p>`;
document.body.appendChild(panel);
findByComputedStyle(panel, { color: 'red' });
// => [p (Out of stock), p.warning, em] (em inherits red from its parent)
findByComputedStyle(panel, { 'font-weight': 'bold', color: 'rgb(255, 0, 0)' });
// => [p.warning, em]
findByComputedStyle(panel, { fontStyle: 'italic' });
// => [em] (italic comes from the browser's default style for em)
findByComputedStyle(panel, { color: 'banana' });
// => []