home ~ socials ~ projects ~ rss

Get The Current Font Size Of An HTML Element In JavaScript

October 2024

Output

The current font size is: ???

HTML

<style>
.item {
  font-size: 1rem;
  border: 1px solid #ccc;
  padding: 1rem;
  margin: 2rem;
}
</style>

<button class="btn" data-go="down">Reduce</button>
<button class="btn" data-go="up">Enlarge</button>

<div class="item">The current font size is: ???</div>
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
Share link:
https://www.alanwsmith.com/en/2n/mm/ds/ci/?get-the-current-font-size-of-an-html-element-in-javascript