user user - 7 months ago 32
Javascript Question

Difference between document.getElementById and document.getElementsByClassName

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.

Answer

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";
    }
}
Comments