admin管理员组文章数量:1341959
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.
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.
Share asked Apr 8, 2013 at 9:30 SoarabhSoarabh 2,9609 gold badges41 silver badges57 bronze badges5 Answers
Reset to default 7getElementsByClassName
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.
You need to loop through the elements:
var elements = document.getElementsByClassName('className');
for (var i = 0; i < elements.length; i++) {
elements[i].style.paddingLeft = paddingOfUl.toString()+"px";
}
document.getElementsByClassName('className')
will return an array of elements. Since an array does not have a style property you receive the error.
The code should iterate over the elements returned by the array.
var elements = document.getElementsByClassName('className');
for(var i = 0; i < elements.length; i++){
elements[i].style.paddingLeft = paddingOfUl.toString() + "px";
}
var elements = document.getElementsByClassName('className');
// the above returns an Array-Like structure with a length property.
for (var i = 0, len = elements.length; i < len; i++) {
elements[i].style.paddingLeft = "10px";
};
You can change style of any element using javascript as follow:
document.getElementById("nameofelement").style.paddingLeft="10px";
instead of paddingLeft you can also use background="color" or color="grren" etc..
本文标签: jqueryPadding Left and Right Using Core JavascriptStack Overflow
版权声明:本文标题:jquery - Padding Left and Right Using Core Javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743687763a2522181.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论