js获取html对象

来源:互联网 发布:美工专用笔记本 编辑:程序博客网 时间:2024/06/08 03:36

  使用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试试看。
这里写图片描述

1 0
原创粉丝点击