根据一些参数遍历HTML表

时间:2019-05-07 07:41:38

标签: javascript html html-table

我正在尝试通过for循环获取HTML表的内部文本,但我想将其基于某些参数。在下面,您将看到我的HTML表的结构:

var Row = document.getElementById("exploreTable");
    var Cells = Row.getElementsByTagName("td");

    l = Cells.length
    var number = 1
    for (var i = 0; i < l; i++, number++ ) {
      console.log(number + ". " + Cells[i].innerText);
    }
<table id="exploreTable">
  <TR>
    <td></td>
    <A name="Explore"></A>
  </TR>
  <tr>
    <td class="ColRow">
      <ul>
        <li>
          <a class="DetailLink" href="...&searchType=subject">
           Labor market
          </a>
          <a class="DetailLink"></a>
        </li>
      </ul>
  </td>
  </tr>
  <tr>
    <td class="ColRow">
      <ul>
        <li>
          <a class="DetailLink" href="....&searchType=subject">
            Sex discrimination in employment.
          </a>
          <a class="DetailLink"></a>
        </li>
      </ul>
  </td>
  </tr>
  <tr>
    <td class="ColRow">
      <ul>
        <li>
          <a class="DetailLink" href="...&searchType=DifferentType">
            Sex discrimination against women.
          </a>
          <a class="DetailLink"></a>
       </li>
      </ul>
  </td>
  </tr>
</table>

我不知道要添加什么,以便我的代码仅迭代到ul / li / a的表td,该表包含包含以下内容的href属性:&searchType=subject。我想获得“劳动力市场”,“就业中的性别歧视”和“对妇女的性别歧视”的文字价值。我在考虑document.evaluate,但不确定从哪里开始或放置代码。预先感谢!

1 个答案:

答案 0 :(得分:2)

尝试使用querySelectorAll()Attribute selector

kubectl exec -it postgres-566fbfb87c-rcbvd sh # env POSTGRES_PASSWORD=example POSTGRES_USER=postgres POSTGRES_DB=postgres # psql -h $(hostname -i) -U postgres Password for user postgres: psql (11.2 (Debian 11.2-1.pgdg90+1)) Type "help" for help. postgres=# \c postgres You are now connected to database "postgres" as user "postgres". postgres=#

  

表示属性名称为 attr 的元素,其值在字符串中至少包含一个值。

[attr*=value]
var Row = document.getElementById("exploreTable");
var Cells = Row.querySelectorAll("td a[href*='&searchType=subject']");

l = Cells.length
var number = 1
for (var i = 0; i < l; i++, number++ ) {
  console.log(number + ". " + Cells[i].innerText);
}