Find elements with given color
<div id="root">
<span id="1" style="color: red">Red</span>
<span id="2" style="color: orange">Orange</span>
<span id="3" style="color: #f00">Red</span>
<span id="4" style="color: #ff0000">Red</span>
<span id="5" style="color: rgb(255, 0, 0)">Red</span>
<span id="6" style="color: black">Black</span>
<span id="7">No Color</span>
<span id="8" style="color: white">
<span id="9">No Color</span>
</span>
</div>
const root = document.getElementById("root");
console.log(findElementsWithColor(root, "red")); // ['1', '3', '4', '5']
console.log(findElementsWithColor(root, "orange")); // ['2']
console.log(findElementsWithColor(root, "black")); // ['root', '6', '7', '9']
console.log(findElementsWithColor(root, "white")); // ['8']
// No color specified is equivalent to black. In UI color may depend on parent's color though.
function getComputedColor(colorCode) {
const div = document.createElement("div");
div.style.color = colorCode;
document.body.appendChild(div);
const { color } = window.getComputedStyle(div);
document.body.removeChild(div);
return color;
}
function findElementsWithColor(root, color) {
const standardColor = getComputedColor(color);
const result = [];
function search(ele) {
const eleColor = ele.style.color;
const eleComputedColor = getComputedColor(eleColor);
if (eleComputedColor === standardColor) {
result.push(ele.id);
}
for (let child of ele.children) {
search(child);
}
}
search(root);
return result;
}