Evgenij Reznik
Evgenij Reznik

Reputation: 18594

Removing elements by ID

I have a table with the following structure:

<table>
  <tr>
    <td>some column|1</td>
    <td id="abc|1">abc</td>
    <td id="abc|1">abc</td>
  </tr>
  <tr>
    <td>another column|1</td>
    <td id="def|1">def</td>
    <td id="def|1">def</td>
  </tr>
  <tr>
    <td>ome column|2</td>
    <td id="abc|2">abc</td>
    <td id="abc|2">abc</td>
  </tr>
  <tr>
    <td>another column|2</td>
    <td id="def|2">def</td>
    <td id="def|2">def</td>
  </tr>
</table>

The content comes from a database.

As you can see, the IDs have the suffix |x. I want to remove all elements with the suffix |2 in the 2nd column and all elements with the suffix |1 in the 3rd column.
Also the 3rd column should be shifted to the top, and all rows ending with |2 in the 1st column should disappear.

So that the final result looks like that:

<table>
  <tr>
    <td>some column|1</td>
    <td id="abc|1">abc</td>
    <td id="abc|2">abc</td>
  </tr>
  <tr>
    <td>another column|1</td>
    <td id="def|1">def</td>
    <td id="def|2">def</td>
  </tr>
</table>

This is my approach, but it doesn't work at all:

$("table td:nth-child(2)").find("[id$=2]").each(function() {
  $(this).hide();
});

$("table td:nth-child(3)").find("[id$=1]").each(function() {
  $(this).hide();
});

Here is the fiddle.

Upvotes: 0

Views: 111

Answers (1)

Tushar
Tushar

Reputation: 87203

ID should be unique. It's better if you can change the HTML and make IDs unique.


IF CHANGING HTML IS NOT POSSIBLE

As both the selector are pointing to same element, use following

$("table td:nth-child(2)[id$=2], table td:nth-child(3)[id$=1]").hide();

Demo

Upvotes: 2

Related Questions