How can i return 2 values with getElementsByClassName()?

This question already has an answer here:

  • Loop through an array in JavaScript 35 answers

  • 使用循环:

    <!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>

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

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

    你可以使用querySelectorAll方法:

    function myFunction() {
        var divs = document.querySelectorAll('.example');
        [].forEach.call(divs, function(div) {
            div.innerHTML = "Hello World!";
        });
    }
    
    链接地址: http://www.djcxy.com/p/24546.html

    上一篇: 记录数组索引,而不是数值(JavaScript)

    下一篇: 我怎样才能返回2个值与getElementsByClassName()?