首页 > 解决方案 > 您如何使用 JavaScript 从内部表的 TD 中影响 DIV?

问题描述

我有一个包含我要阻止的内容的外部 DIV。然而,只有内部 TD 具有作为限定符的属性。

我已经得到了代码(来自一个 SO 用户)并使用 TamperMonkey 来实现它,它就像一个魅力。但是它删除的太少并保留了父 DIV。我对 JavaScript 知之甚少,无法影响外部 DIV。

<DIV>
   <Table></TABLE>
   <Table>
      <td attribute="desiredTarget"></td>
   </TABLE>
   <Table></TABLE>
</DIV>

预期:DIV 不应基于 TD 内容显示结果:DIV 仍显示

标签: javascript

解决方案


使用jQuery会比 PURE JS 更好

$('td[attribute="X"]')
  .parent() //TO TR
  .parent() //TO TBODY
  .parent() //TO TABLE
  .parent() //TO DIV
  .css("background-color", "red"); ///Your command
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  1
  <table border="1">
    <tr>
      <td>Unnesscessary</td>
    </tr>
  </table>
  2
  <table border="1">
    <tr>
      <td attribute="X">xxx</td>
      <td>Unnesscessary</td>
    </tr>
    <tr>
      <td>Unnesscessary</td>
    </tr>
  </table>
  3
  <table border="1">
    <tr>
      <td>Unnesscessary</td>
    </tr>
    <tr>
      <td>Unnesscessary</td>
    </tr>
  </table>

</div>


推荐阅读