1

I'm looking for some kind of "reverse CSS selectors": Given a HTML document how is it possible to look up fragments that have a specific formatting? For instance I would like to get a list of segments that use bold text (font-weight: bold;). Given this document:

<h1>example</h1>
<p>This is <b>an example</b> with <span style="font-weight: bold">formatting</span>.
</p>

The list of segments would then include (for instance given via XPath selectors):

  • /h1[1]
  • /p[1]/b[1]
  • /p[1]/span[1]
TylerH
  • 20,799
  • 66
  • 75
  • 101
Jakob
  • 3,570
  • 3
  • 36
  • 49
  • @Rob Sure it is not! I thought there might be some Browser API, programming library, algorithm etc. to do the lookup. It turns out [getComputedStyle](https://developer.mozilla.org/de/docs/Web/API/Window/getComputedStyle) is the answer! – Jakob Oct 28 '19 at 19:31
  • I see I misunderstood the question. – Rob Oct 28 '19 at 20:03

1 Answers1

2

You can use javascript to loop through all the elements in the DOM and check the font-weight of each element:

window.getComputedStyle(myDOMElement).getPropertyValue('font-weight');

A font-weight of 400 is normal (in CSS, font-weight: normal and font-weight: 400 are identical) so any font-weight above 400 means that the element is bolded.

N.B. In CSS, a font-weight is usually either 400, 700 or 900.

Once you have identified a bolded element, you can apply an identifying class to that element.

Working Example:

const allDOMElements = document.querySelectorAll('*');

for (let i = 0; i < allDOMElements.length; i++) {

  let fontWeight = window.getComputedStyle(allDOMElements[i]).getPropertyValue('font-weight');

  if (fontWeight > 400) {

    allDOMElements[i].classList.add('is-bold');
  }
}
.is-bold {
  color: rgb(255, 0, 0);
}
<h1>Example</h1>
<p>This is <b>an example</b> with <span style="font-weight: bold">formatting</span>.
</p>
Rounin
  • 27,134
  • 9
  • 83
  • 108