Skip to content

How to create a button that increases text by 1px in JavaScript [closed]

I need your help. I’m a beginner in JavaScript and I want to create a button that increases text by 1px. Can you help me?

Answer

This should help! window.getComputedStyle(txt, null).getPropertyValue('font-size'); This is what you can use to get the fontSize of an element.

const txt = document.querySelector("#txt");

function changeFontSize(){
  let fontSize = window.getComputedStyle(txt, null).getPropertyValue('font-size');
  let newFontSize = Number(fontSize.slice(0,2)) + 1
  txt.style.fontSize = `${newFontSize}px`;
 }
#txt {
  font-size: 16px;
 }
<div id="txt">Sample Text</div>
<button onclick="changeFontSize()">Click</button>