如何使用getElementsByClassName()返回2个值?

时间:2016-04-16 08:42:18

标签: javascript

Elm.Main

链接例如:http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_document_getelementsbyclassname

此示例向我们展示了如何将第一个div更改为“hello world”。我想学习如何将所有课程改为“Hello world”。我尝试将elm make Foo.elm Bar.elm --output elm.js更改为<!DOCTYPE html> <html> <body> <div class="example">First div element with class="example".</div> <div class="example">Second div element with class="example".</div> <p>Click the button to change the text of the first div element with class="example" (index 0).</p> <button onclick="myFunction()">Try it</button> <p><strong>Note:</strong> The getElementsByClassName() method is not supported in Internet Explorer 8 and earlier versions.</p> <script> function myFunction() { var x = document.getElementsByClassName("example"); x[0].innerHTML = "Hello World!"; } </script> </body> </html> ,但没有任何反应。任何的想法? :/

3 个答案:

答案 0 :(得分:0)

您必须使用循环才能影响所有元素:

list1

答案 1 :(得分:0)

将循环用作:

&#13;
&#13;
<!DOCTYPE html>
<html>
<body>

<div class="example">First div element with class="example".</div>

<div class="example">Second div element with class="example".</div>

<p>Click the button to change the text of the first div element with class="example" (index 0).</p>

<button onclick="myFunction()">Try it</button>

<p><strong>Note:</strong> The getElementsByClassName() method is not supported in Internet Explorer 8 and earlier versions.</p>

<script>
function myFunction() {
    var x = document.getElementsByClassName("example");
    for(var i = 0; i < x.length; i++)
    x[i].innerHTML = "Hello World!";
}
</script>

</body>
</html>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您可以使用querySelectorAll方法:

function myFunction() {
    var divs = document.querySelectorAll('.example');
    [].forEach.call(divs, function(div) {
        div.innerHTML = "Hello World!";
    });
}