user2964934
user2964934

Reputation: 55

How to find elements based on computed style

I wanted to find all element having specific font color in my selenium automation project. but as the font color style is not inline it will not be visible in DOM. Is there anyway to find elements based on their computed style? may be using xpath or css or finding such elements using JavaScript?

Upvotes: 2

Views: 463

Answers (1)

Vinod Liyanage
Vinod Liyanage

Reputation: 1155

try this,

const color = 'rgb(255, 0, 0)' // use rgb color codes.
const elements = Array.from(document.body.getElementsByTagName("*"));
const specificFontColoredElements = elements.filter(elm => {
  const style = getComputedStyle(elm)
  return style?.color === color
})
console.log(specificFontColoredElements)
h2 {
  color: red;
}

.greencolor {
  color: green
}
<h2>I'm red</h2>
<p>I do not have user styled color!</p>
<h2 class="greencolor">I'm green</h2>

Upvotes: 2

Related Questions