使用Javascript检索TD锚的html表内容

时间:2018-04-25 18:27:37

标签: javascript html-table

我无法理解如何抓取表格行单元格中的href属性。当我尝试这样做时,似乎第二个循环对选定的TR元素不起作用



function asd(){
    this.container = document.getElementsByClassName("cart-contents")[0];
    if (!this.container){
        return false;
    }

    this.itemsContainer = 
    this.container.getElementsByClassName("minicart-table")[0];
    this.itemsTable = this.itemsContainer.getElementsByClassName("views-table")[0];
    this.cartDetails = [];

    for (var i = 0, row; row = this.itemsTable.rows[i]; i++) {
        for (var j = 0, col; col = row.cells[j]; j++) {
            console.log(col[0].getElementsByTagName("a")[0].getAttribute("href"));
        }
        console.log('________________');
    }
}
asd();

<div class="cart-contents">
<div class="minicart-table">
    <table class="views-table">
        <tbody>
          <tr>
            <td class="views-field-field-product-image"><a href="url">text</a></td>
            <td class="tg-yw4l"></td>
           </tr>
        </tbody>
      </table>
  </div>
</div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

使用querySelector()。使用safe。例如:

&#13;
&#13;
var anchor = document.querySelector(".cart-contents a:first-child");

console.log(anchor.getAttribute("href"));
&#13;
<div class="cart-contents">
<div class="minicart-table">
    <table class="views-table">
        <tbody>
          <tr>
            <td class="views-field-field-product-image"><a href="url">text</a></td>
            <td class="tg-yw4l"></td>
           </tr>
        </tbody>
      </table>
  </div>
</div>
&#13;
&#13;
&#13;

此外,以下是修复代码的方法:

for (var i = 0, row; row = this.itemsTable.rows; i++) {
    for (var j = 0, col; col = row[i].cells; j++) {
        console.log(col[j].getElementsByTagName("a")[0].getAttribute("href"));
    }
}

答案 1 :(得分:1)

使用col代替col[0]

function asd(){
    this.container = document.getElementsByClassName("cart-contents")[0];
    if (!this.container){
        return false;
    }

    this.itemsContainer = 
    this.container.getElementsByClassName("minicart-table")[0];
    this.itemsTable = this.itemsContainer.getElementsByClassName("views-table")[0];
    this.cartDetails = [];

    for (var i = 0, row; row = this.itemsTable.rows[i]; i++) { 
        // only the first column
        col = row.cells[0];
        var anchor = col.getElementsByTagName("a")[0];
        if (anchor !== undefined) {
            console.log(anchor.getAttribute("href"));   
        }        
        console.log('________________');
    }
}
asd();
<div class="cart-contents">
<div class="minicart-table">
    <table class="views-table">
        <tbody>
          <tr>
            <td class="views-field-field-product-image"><a href="url">text</a></td>
            <td class="tg-yw4l"></td>
           </tr>
        </tbody>
      </table>
  </div>
</div>