Units mistakes in JavaScript

It is often easy to make a mistake and forget about measuring units. For example:

let width = 100; elem.style.width = width; // oops...

It would be correct to specify the value in pixels:

let width = 100; elem.style.width = width + 'px';

Let's imagine that we want to increase the width by some value. To do this, we first need to read the width, then extract the number, add the desired value to it, add 'px' and only then write it all back:

let widthPx = elem.style.width; let widthNm = parseInt(width); elem.style.width = (widthNm + 30) + 'px';

Explain what is wrong with the following code:

<div style="font-size: 16px;"> text </div> let elem = document.querySelector('div'); elem.style.fontSize = elem.style.fontSize + 2;

Explain what is wrong with the following code:

<div style="font-size: 16px;"> text </div> let elem = document.querySelector('div'); elem.style.fontSize = parseInt(elem.style.fontSize + 2) + 'px';

Explain what is wrong with the following code:

<div style="font-size: 2.5em;"> text </div> let elem = document.querySelector('div'); elem.style.fontSize = parseInt(elem.style.fontSize) + 2 + 'em';

A div is given:

<div id="elem" style="width: 300px; height: 200px; border: 1px solid red;"> text </div>

There is also a button. On button click increase the width and height of the div by 50px.

A div is given:

<div id="elem" style="width: 300px; height: 200px; border: 1px solid red;"> text </div>

There is also a button. On button click increase the width and height of the div by 10%.

enru