Home > Back-end >  Regex Expression to remove any html tag with a given class
Regex Expression to remove any html tag with a given class

Time:10-20

Can anyone help me with a regex expression that I can use to remove any html tag with a given class.

Example -

I have selected all tr in the dom and I have them as a string. But I will like to remove all tr's that has class, "world"..

<tr ></tr>
<tr ></tr>
<tr ></tr>

Note - I have them as a string because I would like to copy them to the clipboard. However, I would like this tag(with a given class) to remain the dom but not in the string I want to copy to the clipboard

CodePudding user response:

A regular expression isn't the right tool for this task.

To do what you require, select the table element from the DOM and clone it. You can then select the child tr.world elements from the cloned table, so you don't affect the instance currently in the DOM, before you get the resulting innerHTML. Here's a working example:

let table = document.querySelector('table').cloneNode(true);
table.querySelectorAll('tr.world').forEach(el => el.remove());
let html = table.querySelector('tbody').innerHTML;

console.log(html);
<table>
  <tr ><td>World</td></tr>
  <tr ><td>Stack</td></tr>
  <tr ><td>Hello world</td></tr>
  <tr ><td>Foo</td></tr>
</table>

  • Related