解析dom中的children對象數組元素firstChild,lastChild的使用

來源:互聯網
上載者:User

複製代碼 代碼如下:
<!--children對象數組元素樣本 -->
<html>
<body>
  <table   id="tbl">  
  <tbody> <tr> <td> 行1列1 </td><td>行1列2 </td></tr>  
  <tr> <td> 行2列1 </td><td>行2列2 </td></tr>
  </tbody>
  </table>  
  <input   onclick="alert(document.all.tbl.children(0).children(0).innerHTML)"   value="children(0)"   type="button">  
  <input   onclick="alert(document.all.tbl.children(0).children(1).innerHTML)"   value="children(1)"   type="button">  
  <input   onclick="alert(document.all.tbl.children(0).children(1).children(0).innerHTML)"   value="children(2)"   type="button">
  <div   id=test>  
  <a></a>  
  <table></table>  
  </div>  

  <script>  
  alert(test.children[0].tagName)  
  alert(test.children[1].tagName)  
  </script>  

</body>
</html>

<!--在DOM中,整個頁面裡的元素是個樹型結構
children 代表對象的子節點數組-->

document.all.tbl.children(0).children(0).innerHTML解釋
document.all.tbl.children(0)定位到table的第一個子節點<tbody>
document.all.tbl.children(0).children(0)定位到table的第一個子節點的第一個子節點<tr>,列印結果<td> 行1列1 </td><td>行1列2 </td>


document.all.tbl.children(0).children(1).innerHTML,列印結果<td> 行2列1 </td><td>行2列2 </td>


document.all.tbl.children(0).children(1).children(0).innerHTML 列印結果行2列2


<!--fistChild,lastChild樣本-->
<html>
<body>
  <table   id="tbl">  
  <tbody> <tr id="tr1"> <td> 行1列1 </td><td>行1列2 </td></tr>  
  <tr> <td="tr2"> 行2列1 </td><td>行2列2 </td></tr>
  </tbody>
  </table>  
  <input   onclick="alert(document.all.tbl.firstChild.firstChild.innerHTML)"   value="children(0)"   type="button">  
  <input   onclick="alert(document.all.tbl.firstChild.lastChild.innerHTML)"   value="children(1)"   type="button">  
  <input   onclick="alert(document.all.tbl.firstChild.lastChild.firstChild.innerHTML)"   value="children(2)"   type="button">
  <div   id=test>  
  <a></a>  
  <table></table>  
  </div>  

  <script>  
  alert(test.firstChild.tagName)  
  alert(test.lastChild.tagName)  
  </script>  

</body>
</html>

document.all.tbl.firstChild定位到table的第一個子節點<tbody>
document.all.tbl.firstChild.firstChild定位到table的第一個子節點<tbody>
的第一個子節點<tr id="tr1">
document.all.tbl.firstChild.firstChild.innerHTML列印結果是<td> 行1列1 </td><td>行1列2 </td>


document.all.tbl.firstChild.lastChild定位到table的第一個子節點<tbody>
的最後子節點<tr id="tr2">
document.all.tbl.firstChild.lastChild.innerHTML列印結果是<td="tr2"> 行2列1 </td><td>行2列2 </td>


document.all.tbl.firstChild.lastChild.firstChild.innerHTML 列印結果是
行2列2

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.