我的页面上有一个表格,它看起来像这样:
<body>
<table class="table table-bordered">
<thead>
<tr>
<th>#</th>
<th>Product name</th>
<th>Product description</th>
<th>Price</th>
<th>Details</th>
</tr>
</thead>
<tbody>
<tr style="height: 50px;">
<td>1</td>
<td>Mug</td>
<td>Perfect for drinking stuff</td>
<td>41</td>
<td><a href="/products/detail?id=1"><i class="glyphicon glyphicon-info-sign"></i></a></td>
</tr>
etc....
</body>
我正在尝试编写一些 javascript 代码来访问“a”标记和 href 属性。 我不能给它一个 id 来轻松访问它所以我试图通过以下方式访问它:
var btn = document.getElementsByTagName("tbody")[0].getElementsByTagName("a")[0];
console.log(btn.href);
但是,我收到以下错误:btn 未定义。
如果我尝试打印出 tbody 元素,它会返回一个对象,所以我不确定为什么这对它的子标签不起作用。
我应该注意到这个 JavaScript 是在 window.onload 函数中执行的。
最佳答案
对于这种特殊情况,最好使用 document.querySelectorAll() :
var btn = document.querySelectorAll("tbody a")[0];
console.log(btn.href);
示例:
var btn = document.querySelectorAll("tbody a")[0];
console.log(btn.href);
<table class="table table-bordered">
<thead>
<tr>
<th>#</th>
<th>Product name</th>
<th>Product description</th>
<th>Price</th>
<th>Details</th>
</tr>
</thead>
<tbody>
<tr style="height: 50px;">
<td>1</td>
<td>Mug</td>
<td>Perfect for drinking stuff</td>
<td>41</td>
<td><a href="/products/detail?id=1"><i class="glyphicon glyphicon-info-sign"></i></a></td>
</tr>
</tbody>
</table>
关于javascript - 嵌套的 GetElementsByClassName 在 window.onload 函数内部返回未定义的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54663096/