Skip to content
Advertisement

Hide elements without knowing complete id

I have a table like below

<table id="categoriesTable">

 <tr id=row_id1_dynamicdata> 
    <td>...</td>
    <td>..</td>
 </tr>

<tr id=row_id2_dynamicdata> 
    <td>...</td>
    <td>..</td>
</tr>

<tr id=row_id3_dynamicdata> 
    <td>...</td>
    <td>..</td>
</tr>

<tr id=row_id4_dynamicdata> 
    <td>...</td>
    <td>..</td>
</tr>

</table>

I want to hide all rows except row whose id contains id4. I won’t have full id. I came up with below jQuery code, but as I don’t have full id, it doesn’t work.

var idValue = document.getElementById(someElement);
$('#categoreisTable').find('tr').not($('#row_' +idValue)).hide();

How to filter with only half the id?

Advertisement

Answer

You can use the “Attribute starts with” selector to find the rows which don’t match the one with the specified idValue. For example:

$('#someElement').on('change', function() {
  var idValue = this.value;
  $('#categoriesTable')
    .find('tr')
    .show()    // not needed if you only want to hide
    .not('[id^="row_id' + idValue + '_"]')
    .hide();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="categoriesTable">

  <tr id=row_id1_dynamicdata>
    <td>.1..</td>
    <td>..</td>
  </tr>


  <tr id=row_id2_dynamicdata>
    <td>.2..</td>
    <td>..</td>
  </tr>

  <tr id=row_id3_dynamicdata>
    <td>.3..</td>
    <td>..</td>
  </tr>

  <tr id=row_id4_dynamicdata>
    <td>.4..</td>
    <td>..</td>
  </tr>

</table>

<input type="text" id="someElement" />
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement