I tried to change all paddings of the html element with js, like:
const pd = 1
document.getElementsByClassName('board')[0].style.paddingRight = pd + 'px'
document.getElementsByClassName('board')[0].style.paddingLeft = pd + 'px'
document.getElementsByClassName('board')[0].style.paddingTop = pd + 'px'
document.getElementsByClassName('board')[0].style.paddingBottom = pd + 'px'
but it sets the padding to 1px.
If one of the lines is removed eg.:
const pd = 1
document.getElementsByClassName('board')[0].style.paddingRight = pd + 'px'
document.getElementsByClassName('board')[0].style.paddingTop = pd + 'px'
document.getElementsByClassName('board')[0].style.paddingBottom = pd + 'px'
other values are set properly.
Can anyone explain why is this happening, and how can I fix it?
When you set the same value (in your example 1px) for the following CSS properties:
padding-bottom,padding-left,padding-right,padding-top (all sides) - it's the same as padding: 1px;.
Moreover, if you set the same value (for example 2px) for padding-right and padding-left, and the same value for padding-top and padding-bottom (for example 1px) - you will see padding: 1px 2px;
Snippet:
var pd = 1;
var pd2 = 2;
document.getElementsByClassName('board')[0].style.paddingTop = pd + 'px'
document.getElementsByClassName('board')[0].style.paddingRight = pd2 + 'px'
document.getElementsByClassName('board')[0].style.paddingBottom = pd + 'px'
document.getElementsByClassName('board')[0].style.paddingLeft = pd2 + 'px'
<div class="board">board</div>
Check this MDN's chart to see all combination.
That's because you are passing an Integer instead a String, in order to change the padding property you should use a string.
There are many ways to solve it but if all the paddings are the same then just modify padding property.
Change your const to string:
const pd = '1';
document.getElementsByClassName('board')[0].style.padding = pd;
'1' is taken as 1px by default, if you want to specify other metrics then write it, like '1em', '1%', etc.
Also, you may use
document.querySelector('.board')
to select the first element with board class instead select all and modify by index
Because I can't comment so i trying to answer
Can you show me your test results and what do you want
There's nothing wrong with your javascript script
If you want to change all the padding why not
selector.style.padding = "1px"
Or
Selector.style.padding = "1px 1px 1px 1px"
What is the reason you type that much? 🤔