js獲取html對象

  使用js獲取html對象有三種方法: getElementById, getElementsByName和getElementsByTagName。

method args result
getElementById id 單個html對象
getElementsByName name 一組html對象
getElementsByTagName tagName 一組html對象

以下是一個html文檔片段:

<p id="pa">It is the first paragraph!</p>
<p name="pb">It is the second paragraph!</p>
<p name="pb">It is the third paragraph!</p>
<table border="1">
        <tr>
            <th>Name</th>
            <th>Age</th>
            <th>Gender</th>
        </tr>
        <tr>
            <td>Alice</td>
            <td>22</td>
            <td>female</td>
        </tr>
        <tr>
            <td>Bob</td>
            <td>23</td>
            <td>male</td>
        </tr>
        <tr>
            <td>David</td>
            <td>22</td>
            <td>male</td>
        </tr>
    </table>

    <script>
        var pa = document.getElementById('pa');
        console.log('pa:', pa);
        var ps = document.getElementsByName('pb');
        console.log('ps:', ps);
        var tds = document.getElementsByTagName('td');
        console.log('tds:', tds);
    </script>

下面是該頁面內容和打印在控制檯上的內容截圖:
這裏寫圖片描述

這下就看的清楚了,通過getElementById只能獲取指定id的單個html對象。而通過標籤的name或者標籤的名字就能獲取到一組html對象了。

ps: csdn上使用的markdown編輯器好像有些問題,好像不太能支持自定義代碼片段。下面對照我本地的md試試看。
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章