0

I'm wanting to hide a parent <tr> tag where a grandchild <span> tag has an ID with a specific string.

Let's say I want to check for the string "test123" in the ID, e.g.

<table>
  <tr id="this_is_a_test456">
    <td>
      <span>
        <span>

        <span>
      </span>
    </td>
  </tr>
  <tr> <<<--- THIS ROW SHOULD BE DELETED
    <td>
      <span>
        <span id="this_is_a_test123">

        <span>
      </span>
    </td>
  </tr>
</table>
Daniel Williams
  • 1,947
  • 3
  • 23
  • 40

1 Answers1

0

Find the <span> within a <tr> by partial ID and if it exists, select the parent row and remove it

let idPartial = 'test123'
let span = document.querySelector(`tr span[id*="${idPartial}"]`)
if (span) {
  span.closest('tr').remove()
}
<table border="1">
  <tr id="this_is_a_test456">
    <td>
      <span>
        <span>My row stays<span>
      </span>
    </td>
  </tr>
  <tr>
    <td>
      <span>
        <span id="this_is_a_test123">My row goes<span>
      </span>
    </td>
  </tr>
</table>

See


The above finds the first element matching your condition ("id attribute contains"). If you wanted to do this for all matching <span> elements, use

let idPartial = 'test123'
document.querySelectorAll(`tr span[id*="${idPartial}"]`).forEach(span => {
  span.closest('tr').remove()
})

As per Why does jQuery or a DOM method such as getElementById not find the element?, make sure your code runs after the document has loaded.

Phil
  • 128,310
  • 20
  • 201
  • 202
  • sorry but how would you implement the "matching all" code? – Daniel Williams Jun 03 '20 at 05:41
  • @DanielWilliams I'm not really sure what you mean. It's at the bottom of my answer – Phil Jun 03 '20 at 05:42
  • @DanielWilliams other than `idPartial` which I didn't include because it's already up the top, that's it. I've updated the second snippet to show the _"whole code"_ – Phil Jun 03 '20 at 06:21