Search code examples
javascriptcsscss-selectorsgetcomputedstyle

Lookup HTML fragments with known CSS properties


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]

Solution

  • 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>