In particular why does document.getElementsById work here
add padding
We want to get the unique element and allocate it in a variable this can be done by making use of getElementById. But when we want to get all the products elements and allocate them in a variable then basically we are using getElementByClassName.
getElementById returns a single DOM element whose ID matches your query. getElementsByClassName returns an HtmlCollection - an array-like structure containing the DOM elements that matched your query. You have to iterate through each element in the array to apply your style.
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";
}
}
document.getElementById("move") returns html element
document.getElementsByClassName("move") returns html collection
style is a property of html element hence, works fine with getElementById
For reference -
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById