Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Padding Left and Right Using Core Javascript

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.

like image 582
Soarabh Avatar asked Sep 09 '26 13:09

Soarabh


1 Answers

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.

like image 73
T.J. Crowder Avatar answered Sep 11 '26 02:09

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!