2016-08-15 37 views
-1

的H1之後,是表我想針對一個表,只有當它涉及含有「編輯共享區」Javascript來針對包含特定文本

下面是HTML呈現我想表中的H1後目標:

<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> 

回答

1

您可以使用: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>

+0

這是真棒,非常感謝!所以〜選擇器意味着'兄弟姐妹'。輝煌。 – Sly

+0

@Sly請參見[通用兄弟選擇器](https://developer.mozilla.org/en-US/docs/Web/CSS/General_sibling_selectors)_「〜組合器分離兩個選擇器,並且僅在第二個元素先於由第一個,和兩個共同的父母。「_ – guest271314

0

下面是一個不使用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>

+0

喜歡它會。看到寫在JQuery工作的「基礎」JS中很有趣。看看那個東西的大小。 – Sly

相關問題