AMD*_*AMD 5 html javascript jquery
我有两张这样的桌子
<table>
<tr>
<td></td>
<td></td>
</tr>
</table>
<table>
<tr>
<td></td>
<td></td>
</tr>
</table>
Run Code Online (Sandbox Code Playgroud)
他们都是一样的.我必须使用纯javascript选择第一个(和第二个).在jQuery中它是$(table:first).
我需要纯粹的javascript
编辑 在询问时错过了一些东西.
如果表格是这样的(有类)我可以使用 getElementByClassName('class')[0]
<table class="class">
<tr>
<td></td>
<td></td>
</tr>
</table>
<table class="class">
<tr>
<td></td>
<td></td>
</tr>
</table>
Run Code Online (Sandbox Code Playgroud)
您可以使用:
var firstTable = document.getElementsByTagName("table")[0]
这是跨浏览器兼容的.
对于较新的浏览器,您可以使用:
var firstTable = document.querySelector("table")
这将选择第一个表.
您可以使用.getElementsByTagName("table")on document,它将返回NodeList包含文档中所有表的内容.NodeLists是类似于数组的对象,表的返回顺序与文档中的顺序相同,因此您可以使用其索引获取第一个元素.
var firstTable = document.getElementsByTagName("table")[0];
Run Code Online (Sandbox Code Playgroud)
NodeLists是实时的
值得注意的是,NodeList返回的.getElementsByTagName()是实时的,这意味着如果你在调用之后进行DOM操作.getElementsByTagName(),那些操作将反映在你的列表中.
var tables = document.getElementsByTagName("table");
var firstTableBefore = tables[0];
/*
If you then prepend a new table to the body at this point, calling tables[0]
again will now return the newly added element
*/
var firstTableAfter = tables[0];
// firstTableBefore and firstTableAfter will NOT be the same
Run Code Online (Sandbox Code Playgroud)