0

I have the following html that I cannot modify. (It is being auto-generated)

<table>
  <tbody>
    <tr>
      <th>UserName</th>
      <td>Bob</td>
    </tr>
    <tr>
      <th>Password</th>
      <td>Fred</td>
    </tr>
  </tbody>
</table>

This would display:

UserName  Bob
Password  Fred

However, I can insert code inside the td area. I would like to hide the parent row using javascript or css.

Example

For example, if I wanted to hide the second row I can insert javascript:

<table>
  <tbody>
    <tr>
      <th>UserName</th>
      <td>Bob</td>
    </tr>
    <tr>
      <th>Password</th>
      <td>Fred <script type="text/javascript">document.parentrow.hide();</script> </td>
    </tr>
  </tbody>
</table>

And then it should just display

UserName  Bob

Notes

  • The function document.parentrow.hide(); does not work but it is just to show an example of what I am looking for. I would like a function that hides the current row associated with that td.

  • I cannot add custom class or id to the tr tags since I have no control over that portion of the html.

  • I did take a look at the provided link How may I reference the script tag but it is just a general topic. It does not have the answer to my question regarding table rows. It does not relate to accessing rows neither. The link is for accessing loaded javascript files.

Robert Smith
  • 302
  • 3
  • 13
  • Why not include a css file which hides it. You can dynamically add a css file via javascript – Steve Tomlin Mar 29 '23 at 15:50
  • @SteveTomlin You still have the problem of how to specify which row to hide in CSS. There's no class or ID on the row. – Barmar Mar 29 '23 at 15:51
  • See the linked question to get a reference to the current script tag. Then use `.closest("tr")` to get the parent row. – Barmar Mar 29 '23 at 15:53
  • Barmar you closed my question but the link you reference does not answer the question. It is only a general information link. – Robert Smith Mar 29 '23 at 16:09

1 Answers1

1

const secondRow = document.querySelector('tr:nth-child(2)')
secondRow.hidden = true
<table>
  <tbody>
    <tr>
      <th>UserName</th>
      <td>Bob</td>
    </tr>
    <tr>
      <th>Password</th>
      <td>Fred</td>
    </tr>
  </tbody>
</table>
Konrad
  • 21,590
  • 4
  • 28
  • 64