Skip to main content

getElementByStyles

/**
* @param {Element} element
* @param {string} property
* @param {string} value
* @return {Array<Element>}
*/
export default function getElementsByStyle(element, property, value) {
const results = [];

function traverse(node) {
// only process element node
// if (node.nodeType === Node.ELEMENT_NODE) {
// const styleValue = node.style?.getPropertyValue(property);
// if (styleValue === value) {
// results.push(node);
// }
// for (const child of node.children) {
// traverse(child);
// }
// }
for (const child of node.children) {
const styleValue = child.style?.getPropertyValue(property);
if (styleValue === value) {
results.push(child);
}
traverse(child);
}
}
traverse(element);

return results;
}

/**
* const doc = new DOMParser().parseFromString(
`<div>
<span style="font-size: 12px">Span</span>
<p style="font-size: 12px">Paragraph</p>
<blockquote style="font-size: 14px">Blockquote</blockquote>
</div>`,
'text/html',
);

getElementsByStyle(doc.body, 'font-size', '12px');
// [span, p] <-- This is an array of elements.
*/