getElementByTagName not working?

前端 未结 3 1352

In the code below, I am applying a different background color to all even rows by dynamically assigning the class \"even\" to them using javascript. I am calling the alternamte(

3条回答
  •  遥遥无期
    2021-01-21 12:48

    It's getElementsByTagName(), plural. It returns a HTMLCollection

    var table = document.getElementsByTagName("table")[0];   
    

    (if you're confident that there's a

    on the page.)

    If you want to do things to all the

    elements, you'd have to do something like this:

        var tables = document.getElementsByTagName("table");   
    
        for (var ti = 0; ti < tables.length; ++ti) {
          var rows = tables[ti].getElementsByTagName("tr");   
          for(var i = 0; i < rows.length; i++){           
            //change style of even rows 
            //(odd integer values, since we're counting from zero)
            if(i % 2 == 0){ 
                rows[i].className = "even"; 
            }     
          }   
        }
    

    提交回复
    热议问题