getElementByTagName not working?

前端 未结 3 1290

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 <table> on the page.)

    If you want to do things to all the <table> 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"; 
            }     
          }   
        }
    
    0 讨论(0)
  • 2021-01-21 12:49

    getElementsByTagName() returns an array matching the selector. Hence try

    var table = getElementsByTagName('table')[indexnumber];
    
    0 讨论(0)
  • 2021-01-21 12:57

    Use getElementsByTagName instead of getElementByTagName (getElementsByTagName return multiple node elements )

     var table = document.getElementsByTagName("table")[0], trs, rl;  
     vat tl= table.length;
     while(tl--){
            trs = tables[tl].getElementsByTagName("tr");
            rl = trs.length;
            while(rl--){
               if(rl % 2 == 0){ 
                  trs[rl].className = "even"; 
               } 
            }
      }
    
    0 讨论(0)
提交回复
热议问题