I am trying to set padding left and right using javascript using this code but its not working
document.getElementsByClassName('className').style.paddingLeft = paddingOfUl.toString()+"px" ;
Getting this error
Uncaught TypeError: Cannot set property 'paddingLeft' of undefined
Please help suggest me what I am doing wrong here.
getElementsByClassName returns a list of elements, not one element. You need to index into the list to modify an element in it.
Just the first one:
document.getElementsByClassName('className')[0].style.paddingLeft = paddingOfUl.toString()+"px" ;
// Change here -----------------------------^^^
All of them:
var list = document.getElementsByClassName('className');
var i;
var padding = paddingOfUl.toString()+"px";
for (i = 0; i < list.length; ++i) {
list[i].style.paddingLeft = padding;
}
Separately: There's no need to explicitly call toString on paddingOfUl, it'll get done automatically if you try to append a string to a number. So:
...paddingLeft = paddingOfUl + "px";
...is fine.
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