如何在树中查找元素和兄弟

时间:2016-08-18 17:45:00

标签: jquery html css

我有代码通过选择重复的thead元素来删除重复的行。它删除了最后一个thead元素但是如何选择未删除的thead元素中的元素并执行以下操作:

  • 选择第一个<span>元素并将其隐藏
  • 选择第二个<span>元素并显示

到目前为止,我知道我可以使用find()方法查找第一个span,我知道我可以使用nth-of-type(2)来查找它的兄弟。

我不想为td或span元素提供任何进一步的类或id名称。请不要使用hiddenspan类名来显示。

CSS

.hiddenspan {
display: none;
}

HTML

<table id="test">
  <thead class="test className">
    <tr>
      <td>test1<td>
    </tr>
    <tr>
      <td>test2</td>  
      <td><span>some text</span>
          <span class="hiddenspan">some other text</span>
      </td>
    </tr>
 </thead>
 <thead class="test className">
   <tr>
     <td>test1<td>
   </tr>
   <tr>
     <td>test2<td>
   </tr>
 </thead>
</table>

我想要这个结果

<table id="test">
 <thead class="test className">
  <tr>
   <td>test1<td>
  </tr>
  <tr>
   <td>test2</td>  
   <td><span>some other text</span></td>
  </tr>
 </thead>
</table>

Jquery的:

var $thead = $('thead.test.className:contains(test1)');

if ($thead.length > 1) {
  $thead.not(':first').remove()
}

2 个答案:

答案 0 :(得分:3)

我认为最好的方式

$("#test span:nth-child(1)").hide();

$("#test span:nth-child(2)").show();

答案 1 :(得分:2)

以下是我必须添加到您提供的代码中的内容:

<强> HTML:

<table id="test">
    <thead class="test className">
        <tr>
            <td>test1<td>
        </tr>
        <tr>
            <td>test2</td>  
            <td><span>some text</span>
                <span class="hiddenspan">some other text</span>
            </td>
        </tr>
    </thead>
    <thead class="test className">
        <tr>
            <td>test1<td>
        </tr>
        <tr>
            <td>test2<td>
        </tr>
   </thead>
</table>

<强> CSS:

.hiddenspan {
    display: none;
}

<强> JS:

var $thead = $('thead.test.className:contains(test1)');

if ($thead.length > 1) {
  $thead.not(':first').remove()
  $("span:nth-child(1)").hide();
  $("span:nth-child(2)").show();
}  

以下是JSFiddle