Search code examples
javascripthtmlcssgetcomputedstyle

Use getComputedStyle to identify the CSS font-weight for all P tags


Objective

  • To use getComputedStyle to identify the CSS font-weight assigned to text in a page and note this as text into a span at the start of the P tag/s.

Reason

  • To create a bookmarklet for personal use in identifying where CSS is used to apply strong/bolded text visually. Then a determination can be made if the CSS should be replaced with HTML strong.

Issues

  • Only applies to first P tag in the page.
  • Replaces existing text rather than adding to the existing word/s.

Code so far

var newClass = document.getElementsByTagName('p')
var length = newClass.length;
for (var i = 0; i < length; i++) {
  newClass[i].className =  newClass[i].className + "font--weight"
}

let pAll = document.querySelector('p.font--weight');
let calcStyles = window.getComputedStyle(pAll);
pAll.textContent = 'My computed font-weight is ' + calcStyles.getPropertyValue('font-weight');
pAll.innerHTML = '<span>' + pAll.textContent + '</span>'; 
  • Is this possible, if no there ends the question.
  • Is there a better way to achieve this?
  • Needed in JavaScript not jQuery.

Solution

  • Use el.querySelectorAll() to get the nodeList, el.querySelector() will return the first node of the selector only. Then you just need to use getComputedStyle(selector).getPropertyValue('style') to get the computed style. From there is just concatenating the strings together and setting the innerHTML or textContent to the string.

    Once you have the nodeList, run the elements through a loop to get each one.

    let pTagClass = document.querySelectorAll('.check-weight')
    
    function getFontWeight(els) {
      els.forEach(weight => {
        // weight now represents each individual node in 
        // our nodeList that was passed into the function
        let compStyle = getComputedStyle(weight).getPropertyValue('font-weight');
        let str = `<span class="bookmark">font-weight is: ${compStyle},</span>`
        let currentText = weight.textContent
        weight.innerHTML = `${str} ${currentText}`
      })
    }
    
    getFontWeight(pTagClass)
    .check-weight {
      font-family: "Bahnschrift", sans-serif;
    }
    
    .heavy {
      font-weight: bold;
    }
    
    .normal {
      font-weight: normal;
    }
    
    .light {
      font-weight: lighter;
    }
    
    .bookmark {
      font-weight: normal;
      font-size: smaller;
      background-color: yellow;
      padding: 2px;
    }
    <p class="heavy check-weight">This is a heavy weight</p>
    <p class="heavy check-weight">This is also a heavy weight</p>
    <p class="light check-weight">This is a light weight</p>
    <p class="normal check-weight">This is normal</p>