0

I decleared a <table> inside my JSP page. Using JavaScript, I want to delete all <tr>s whose id contains ;.

For example:

<tr id=";1234;">
   ...
   ...
</tr>

The entire line must be deleted. Someone can give me a tip?

Sebastian Simon
  • 14,320
  • 6
  • 42
  • 61
RemovedQuasar
  • 13
  • 1
  • 9

3 Answers3

1

document.querySelectorAll('tr[id*=";"]').forEach(node => node.remove());
<table>
  <tr id=";1234;">
    <td>Remove Me</td>
  </tr>
  <tr>
    <td>Keep Me</td>
  </tr>
</table>
4castle
  • 28,713
  • 8
  • 60
  • 94
1

You can programmatically remove all <tr> elements with an id containing a ; by executing the following snippet:

Array.from(document.querySelectorAll('tr[id*=";"]')).forEach(tr => {
  tr.remove()
})

Following links for reference:

Patrick Roberts
  • 40,065
  • 5
  • 74
  • 116
0

The EASIEST way to do this is as follows AND is cross-browser (non-ECMA6) compatible.

https://jsfiddle.net/dfju8xn8/1/

<table>
<tr id=";1234;">
<td>foo</td>
</tr>

<tr id="yadayada">
<td>moo</td>
</tr>
</table>

and Javascript

var myElements = document.querySelectorAll('tr[id*=";"]');

for (var xx = 0; xx < myElements.length; xx++) {
   myElements[xx].outerHTML ='';
}

p.s. For readability sake, you should use one of the methods above. If you are going to have to iterate over a large result set, consider that for loops are tested as executing faster.

E. Maggini
  • 7,228
  • 5
  • 23
  • 36
  • `myElements[xx].parentNode.removeChild(myElements[xx]);` is better. – Sebastian Simon Sep 19 '17 at 17:42
  • @Xufox Could you explain why, please? Yours requires a call to the parent node, followed by a function call. Mine wipes the desired chunk of HTML directly. – E. Maggini Sep 19 '17 at 18:14
  • 1
    Setting `innerHTML` or `outerHTML` isn’t just a simple string operation or property access. There’s lots of DOM-reparsing happening after that which is probably slower than a simple DOM node removal. There’s also the possible issue of [accidentally killing event listeners](https://stackoverflow.com/q/5113105/4642212). You _could_ also use `myElements[xx].remove()`, but you were talking about cross-browser compatibility. `outerHTML` actually has compatibility issues of its own and `remove` or `removeChild` is a much more intuitive method for what is being done here. – Sebastian Simon Sep 19 '17 at 18:24
  • Thanks for the clarification :) – E. Maggini Sep 19 '17 at 19:42