Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
368 views
in Technique[技术] by (71.8m points)

javascript - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...