Difference between document.getElementById and document.getElementsByClassName

后端 未结 4 1410
闹比i
闹比i 2020-12-09 14:15

In particular why does document.getElementsById work here

add padding
相关标签:
4条回答
  • 2020-12-09 14:25

    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.

    0 讨论(0)
  • 2020-12-09 14:34

    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.

    0 讨论(0)
  • 2020-12-09 14:35

    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";
        }
    }
    
    0 讨论(0)
  • 2020-12-09 14:40
    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

    0 讨论(0)
提交回复
热议问题