0

If i have similar requirement where I want to create an array with all the <tr>. I want to split with start <tr> and </tr>. How can i give both start and end in split function.

<!DOCTYPE html>
<html>
<body>

<h2>Basic HTML Table</h2>

<table style="width:100%">
  <tr>
    <th>Firstname</th>
 
  </tr>
  <tr>
    <td>Jill</td>
   
  </tr>
  <tr>
    <td>Eve</td>

  </tr>
  <tr>
    <td>John</td>
   
  </tr>
</table>

</body>
</html>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
user15895653
  • 135
  • 8

1 Answers1

2

Don't use split

const arr = [...document.querySelectorAll('tr')].map(tr  => tr.outerHTML)
console.log(arr)

// if the source is a string:

const tblString = `<table style="width:100%"><tr><th>Firstname</th></tr><tr><td>Jill</td></tr><tr><td>Eve</td></tr><tr><td>John</td></tr></table>`

const domFragment = document.createElement('div')
domFragment.innerHTML = tblString;
const arr1 = [...domFragment.querySelectorAll('tr')].map(tr  => tr.outerHTML)
console.log(arr1)
<!DOCTYPE html>
<html>

<body>

  <h2>Basic HTML Table</h2>

  <table style="width:100%">
    <tr>
      <th>Firstname</th>
    </tr>
    <tr>
      <td>Jill</td>
    </tr>
    <tr>
      <td>Eve</td>
    </tr>
    <tr>
      <td>John</td>
    </tr>
  </table>

</body>

</html>
mplungjan
  • 169,008
  • 28
  • 173
  • 236