There are some css
values that is defined with a number, such as opacity
I know while writing css, I would do:
#element {
opacity: 1; /* without a quote mark, just 1 */
}
But when I am going to modify that opacity
with javascript, what should I provide ? only 0.5
or "0.5"
?
if I run:
typeof document.getElementById('element').style.opacity // returns "srting"
So I used to provide string while modifying that. But someone reviewing my code, suggested me to provide number like:
document.getElementById('element').style.opacity = 0.5
What type should actually be used here while modifying it with javascript ? String or Number ?
JavaScript Number toString() The toString() returns a number as a string.
How to convert a string to a number in JavaScript using the parseInt() function. Another way to convert a string into a number is to use the parseInt() function. This function takes in a string and an optional radix. A radix is a number between 2 and 36 which represents the base in a numeral system.
The JavaScript Number type is a double-precision 64-bit binary format IEEE 754 value, like double in Java or C#. This means it can represent fractional values, but there are some limits to what it can store. A Number only keeps about 17 decimal places of precision; arithmetic is subject to rounding.
In JavaScript, there are three ways to write a string — they can be written inside single quotes ( ' ' ), double quotes ( " " ), or backticks ( ` ` ).
All css values are strings (technically, DOMString
s), therefore it's cleaner to use strings as well when you change them. Still, you can use numbers (or whatever) directly, JS will just do .toString()
for you.
However, there are only a few unitless properties in css, for other numeric props you're required to provide a unit, and a bare number would be a mistake:
style.opacity = "0.5" // fine
style.opacity = 0.5 // fine
style.width = "3px" // fine
style.width = 3 // wrong!
So I'd make it a habit to always use strings with css.
Also, document.getElementById('element').style
returns a huge object with all the possible css properties and their values which are strings:
example:
alignContent: ""
alignItems: ""
alignSelf: ""
alignmentBaseline: ""
all: ""
animation: ""
animationDelay: ""
Try it in your browser console on a valid element, you'll see it. So I would suggest using strings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With