当前位置: 代码迷 >> JavaScript >> 嵌套的GetElementsByClassName在window.onload函数内部返回未定义的错误 例:
  详细解决方案

嵌套的GetElementsByClassName在window.onload函数内部返回未定义的错误 例:

热度:22   发布时间:2023-06-12 13:56:52.0

我的页面上有一张桌子,看起来像这样:

<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函数中执行。

对于这种特殊情况,最好使用 :

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> 

  相关解决方案