home ~ projects ~ socials

Get The Current Font Size Of An HTML Element In JavaScript

The current font size is: ???

JavaScript

function getFontSize(el) {
  const styles = window.getComputedStyle(el)
  const size = parseFloat(styles.getPropertyValue('font-size'))
  return size
}

function changeSize(event) {
  const button = event.target
  const item = document.querySelector('.item')
  if (button.dataset.go === "up") {
    item.style.fontSize = `${getFontSize(item) * 1.1}px`
  } else {
    item.style.fontSize = `${getFontSize(item) * 0.9}px`
  }
  item.innerHTML = `The current font size is: ${getFontSize(item)}`
}

document.addEventListener('DOMContentLoaded', () => {
  const buttons = document.querySelectorAll('.btn')
  buttons.forEach((btn) => {
    btn.addEventListener('click', changeSize)
  })
})
-- end of line --

References