Javascript瞄准一个表,该表位于包含特定文本的H1之后

Javascript to target a table that comes after an H1 containing specific text

本文关键字:于包含 文本 之后 H1 一个 Javascript      更新时间:2023-09-26

我想只在包含'编辑共享区域'的H1之后才针对表

这是显示我想要的目标表的html:

<h1>Editing Shared Regions</h1>
<ul class="smartbar">
 <li class="selected"><a href="/core/apps/content/page/?id=-1">Regions</a></li>
</ul>
<table>
    <thead>
        <tr>
            <th>Region</th>
            <th>Type</th>
            <th>Items</th>
                            <th class="action"></th>
            <th class="action"></th>
        </tr>
    </thead>
    <tbody>

您可以使用:contains(),一般兄弟选择器~

 $("h1:contains('Editing Shared Regions') ~ table")
.css("color", "blue")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Editing Shared Regions</h1>
<ul class="smartbar">
  <li class="selected"><a href="/core/apps/content/page/?id=-1">Regions</a>
  </li>
</ul>
<table>
  <thead>
    <tr>
      <th>Region</th>
      <th>Type</th>
      <th>Items</th>
      <th class="action"></th>
      <th class="action"></th>
    </tr>
  </thead>
  <tbody>
</table>

下面是一个不使用jQuery的示例。我不应该扩展DOM,但是编写像guest271314的例子这样的一行代码会很有趣。

NodeList.prototype.contains = function(searchText) {
  for (var ix = 0; ix < this.length; ix++) {
    if (this.item(ix).innerText.trim() === searchText) {
      return this.item(ix);
    }
  }
  return null;
}
Node.prototype.findNext = function(tag) {
  var el = this;
  while (el.nextSibling) {
    el = el.nextSibling;
    if (el.tagName && el.tagName.toUpperCase() === tag.toUpperCase()) {
      return el;
    }
  }
  return null;
}
document.querySelectorAll('h1').contains('Editing Shared Regions').findNext('table').style.color = 'red';
<link href="//cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css" rel="stylesheet"/>
    <div class="container">
        <h1>A Heading</h1>
        <table>
            <tr>
                <td>This is not the table you're looking for</td>
            </tr>
        </table>
        <h1>Editing Shared Regions</h1>
        <ul class="smartbar">
            <li class="selected"><a href="/core/apps/content/page/?id=-1">Regions</a></li>
        </ul>
        <table>
            <thead>
                <tr>
                    <th>Region</th>
                    <th>Type</th>
                    <th>Items</th>
                    <th class="action"></th>
                    <th class="action"></th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>PNW</td>
                    <td>Land</td>
                    <td>meow</td>
                    <td>x</td>
                    <td>y</td>
                </tr>
            </tbody>
        </table>
    </div>