Billy
Billy

Reputation: 2963

How to find elements and siblings within a tree

I have code which deletes duplicate rows by selecting duplicated thead elements. It removes the last thead element however how would I select the elements within the thead element that is NOT removed and do the following:

So far I know I can use the find() method to find the first span and I know I can use nth-of-type(2) to find its sibling.

I do not want to give the td or span elements any further class or id names. And please not to use the hiddenspan class name to show.

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>

I would like this result

<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()
}

Upvotes: 1

Views: 65

Answers (2)

Grizzly
Grizzly

Reputation: 5953

Here is what I have to add to your provided code:

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();
}  

Here is a JSFiddle for you.

Upvotes: 2

Provie9
Provie9

Reputation: 379

The best way i think

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

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

Upvotes: 3

Related Questions