Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
171
rated 0 times [  176] [ 5]  / answers: 1 / hits: 16545  / 9 Years ago, wed, august 12, 2015, 12:00:00

In particular why does document.getElementsById work here



<div id=move>add padding</div>

<button type=button onclick=movefun()>pad</button>

<script>
function movefun() {
document.getElementById(move).style.paddingLeft = 50px;
}
</script>


but document.getElementsByClassName does not work



<div class=move>add padding</div>

<button type=button onclick=movefun()>Set left padding</button>

<script>
function movefun() {
document.getElementsByClassName(move).style.paddingLeft = 50px;
}
</script>


I have left out the common things like the html and body tag to cut down on code length.


More From » jquery

 Answers
19

Because getElementsByClassName returns an array-like object of all child elements which have all of the given class names.



Use this instead if you want to do it by class



DEMO 1 -> http://jsfiddle.net/1r0u5d3o/2/



document.getElementsByClassName(move)[0].style.paddingLeft = 50px;



Or if you want to do it to all the elements of the class, use a loop



DEMO 2 -> http://jsfiddle.net/1r0u5d3o/1/



function movefun() {
var elements = document.getElementsByClassName(move);
for (var i = 0; i < elements.length; i++) {
elements[i].style.paddingLeft = 50px;
}
}

[#65431] Monday, August 10, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
trinity

Total Points: 591
Total Questions: 102
Total Answers: 106

Location: Singapore
Member since Sun, Jul 25, 2021
3 Years ago
trinity questions
Fri, Jan 14, 22, 00:00, 2 Years ago
Tue, Apr 27, 21, 00:00, 3 Years ago
Sun, Mar 14, 21, 00:00, 3 Years ago
;