简体   繁体   中英

Hide a parent element if ID contains specific text string with vanilla Javascript

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, eg

<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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM