【问题标题】:How can you target a child element of an iterated object in JavaScript?如何在 JavaScript 中定位迭代对象的子元素?
【发布时间】:2018-02-02 07:27:47
【问题描述】:

在这种情况下,我只想定位具有 thead 标签的表。

我尝试使用更快的 JavaScript 或 jQuery 进行连接或搜索。

例如thead = DT[i].children('thead');

function go() {
  var i = 0,
    DT = document.getElementsByClassName('DT');
  for (i; i < DT.length; ++i) {
    var x = DT[i];

    if ($(x + ' thead').length) {
      //do stuff to this table
    }
  }
}
<table class="DT" id="gv1">
  <tbody>
    <tr>
      <th>th</th>
    </tr>
    <tr>
      <td>td</td>
    </tr>
  </tbody>
</table>

<table class="DT" id="gv2">
  <thead>
    <tr>
      <th>thead</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>td</td>
    </tr>
  </tbody>
</table>

【问题讨论】:

    标签: javascript jquery foreach each


    【解决方案1】:

    你不需要任何循环,你可以使用 jQuery 的:has() 选择器根据元素是否包含指定的子元素来检索它,像这样:

    function go() {
      $('.DT').has('thead').addClass('foo');
    }
    
    go();
    .foo { border: 1px solid #C00; }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <table class="DT" id="gv1">
      <tbody>
        <tr>
          <th>th</th>
        </tr>
        <tr>
          <td>td</td>
        </tr>
      </tbody>
    </table>
    
    <table class="DT" id="gv2">
      <thead>
        <tr>
          <th>thead</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>td</td>
        </tr>
      </tbody>
    </table>

    【讨论】:

    • $('.DT thead').parent().addClass('foo'); 这也会做同样的事情,不是吗?
    • 是的,虽然有点冗长
    • 感谢罗里,这让我走上了正轨。根据 jQuery 的建议,我选择了 $('.DT').has('thead')api.jquery.com/has-selector
    • 很高兴你把它整理好了。老实说,我以前没有在文档中看到过这个警告。如果这个问题将来有任何访问者,我会更新答案。
    【解决方案2】:

    您可以使用querySelector 来检查嵌套的thead 是否存在。

    if (x.querySelector("thead")) {
      //do stuff to this table
    }
    

    你知道,你这样做是为了完成你最初尝试的事情:

    if ($(x).find("thead").length) {
      //do stuff to this table
    }
    

    这只是为了展示如何从给定的上下文中执行 DOM 选择。

    【讨论】:

    • 虽然has 似乎是要走的路,但我在让它与循环一起工作时遇到了一些问题,你的find 解决方案对我来说是一种享受。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-02-09
    • 1970-01-01
    • 2011-05-13
    • 1970-01-01
    • 2018-04-06
    • 2016-11-08
    • 2018-07-22
    相关资源
    最近更新 更多