Search code examples
javascriptdomdom-node

dom childNodes issue


I seem to be getting different results of fromDate between Mozilla and IE. Is there a more reliable cross-browser way of doing this? [edit] I am actually getting different column values! [/edit]

<tr id='id3332201010241'  />
 <td>20101024</td>
 <td>20101025</td>
 <td>1415</td>
 <td>1445</td>
 <td>INVDROP</td>  
 <td>H4T1A3</td> 
 <td><a href='#' onclick='selectEditActivity("id3332201010241");' >Click Here</a></td>
</tr>

function selectEditActivity(pass_id){ 
 row = document.getElementById(pass_id);    
 var seq = document.getElementById(pass_id).getAttribute("seq");
 var from_date   = row.childNodes[1].innerHTML; 
 alert(from_date);
 var to_date   = row.childNodes[3].innerHTML;  
}

Solution

  • You are seeing the result of differences in how different browsers handle white-space. Instead (for more general cases) you can use getElementsByTagName() to for sure get a certain type of child element (<td> in this case), like this:

    function selectEditActivity(pass_id){ 
      var row = document.getElementById(pass_id),
          cells = row.getElementsByTagName("td"),
          seq = row.getAttribute("seq"),
          from_date = cells[0].innerHTML,
          to_date = cells[1].innerHTML;  
      alert("From: " + from_date + "\nTo: " + to_date);
    }
    

    You can test it out here. As @patrick points out though, it's not needed here, just use the .cells of the <tr>, like this:

    function selectEditActivity(pass_id){ 
      var row = document.getElementById(pass_id),
          seq = row.getAttribute("seq"),
          from_date = row.cells[0].innerHTML,
          to_date = row.cells[1].innerHTML;  
      alert("From: " + from_date + "\nTo: " + to_date);
    }
    

    You can test it out here.