Home > OS >  JS / CSS - How to match element containing string
JS / CSS - How to match element containing string

Time:12-28

I am working with an HTML file that is generated by an old system, so I am not in control of the HTML code generation, unfortunately.

The HTML code looks like the below:

<table cellpadding=10>
  <tr>
    <th>Col 1</th>
    <th>Col 2</th>
    <th>Col 3</th>
  </tr>
  <tr>
    <td>Name: XYZ</td>
    <td>Lorem Ipsum Description</td>
    <td>More Lorem Ipsum</td>
  </tr>
  <tr>
    <td>Name: XYZ</td>
    <td>Lorem Ipsum Description</td>
    <td>More Lorem Ipsum</td>
  </tr>
  <tr>
    <td>Name: 123</td>
    <td>Lorem Ipsum Description</td>
    <td>More Lorem Ipsum</td>
  </tr>
  <tr>
    <td>Name: XYZ</td>
    <td>Lorem Ipsum Description</td>
    <td>More Lorem Ipsum</td>
  </tr>
  <tr>
    <td>Name: XYZ</td>
    <td>Lorem Ipsum Description</td>
    <td>More Lorem Ipsum</td>
  </tr>
</table>

The table contains 1 row for the Table Header, and then 4 rows of data.
As you can see, the first cell of the third row of data has a different text Name: 123.

I need to hide/remove the row Name: 123.

So far I've tried using CSS, but there is no selector that will allow me to match an element that contains a given String.

How can I hide/remove the row Name: 123? I'm happy to use CSS or JS if need be.

CodePudding user response:

Pick up a node list of all the first child elements (i.e. the first cell) of each row, and iterate over them. If its text content matches "Name: 123" then remove its parent node (the row element) from the DOM.

const cells = document.querySelectorAll('tr td:first-child');

for (let i = 0; i < cells.length; i  ) {
  if (cells[i].textContent === 'Name: 123') {
    cells[i].parentNode.classList.add('hidden');
    break;
  }
}
.hidden { display: none; }
<table cellpadding=10>
  <tr>
    <th>Col 1</th>
    <th>Col 2</th>
    <th>Col 3</th>
  </tr>
  <tr>
    <td>Name: XYZ</td>
    <td>Lorem Ipsum Description</td>
    <td>More Lorem Ipsum</td>
  </tr>
  <tr>
    <td>Name: XYZ</td>
    <td>Lorem Ipsum Description</td>
    <td>More Lorem Ipsum</td>
  </tr>
  <tr>
    <td>Name: 123</td>
    <td>Lorem Ipsum Description</td>
    <td>More Lorem Ipsum</td>
  </tr>
  <tr>
    <td>Name: XYZ</td>
    <td>Lorem Ipsum Description</td>
    <td>More Lorem Ipsum</td>
  </tr>
  <tr>
    <td>Name: XYZ</td>
    <td>Lorem Ipsum Description</td>
    <td>More Lorem Ipsum</td>
  </tr>
</table>

  • Related