Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to delete a range of rows using javascript (Vanilla or JQuery)

I need to delete table rows in range from row with an ID "#deleteFirstRow" to row with an ID "#deleteLastRow". But all the other rows out of these two IDs should remain.
NB: I tried to search posted answers but did not get any working solution. Please help!

This is my table:


<table>

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

    <tr id="deleteFirstRow">deleteRow</tr>
    <tr>deleteRow</tr>
    <tr>deleteRow</tr>
    <tr>deleteRow</tr>
    <tr id="deleteLastRow">deleteRow</tr>

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

</table>

I tried this code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$("table tr:not(#deleteFirstRow, #deleteLastRow)").remove();

But this code removes all rows except the ones with IDs: "#deleteFirstRow" and "#deleteLastRow".

What I want is to remove only rows between "#deleteFirstRow" and "#deleteLastRow" and also remove "#deleteFirstRow" and "#deleteLastRow".

So the expected result should be like below:


<table>

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

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

</table>

>Solution :

You can slice the collection of all rows based on the two boundary elements, then call remove.

const rows = $('table tr');
rows.slice(rows.index($('#deleteFirstRow')), 
            rows.index($('#deleteLastRow')) + 1).remove();
tr {
  display: block;
  border: 1px solid;
  padding: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
    <tr class="doNotDeleteRow"><td>1</td></tr>
    <tr class="doNotDeleteRow"><td>2</td></tr>
    <tr class="doNotDeleteRow"><td>3</td></tr>
    <tr id="deleteFirstRow"><td>4</td></tr>
    <tr class="deleteRow"><td>5</td></tr>
    <tr class="deleteRow"><td>6</td></tr>
    <tr class="deleteRow"><td>7</td></tr>
    <tr id="deleteLastRow"><td>8</td></tr>
    <tr class="doNotDeleteRow"><td>9</td></tr>
    <tr class="doNotDeleteRow"><td>10</td></tr>
    <tr class="doNotDeleteRow"><td>11</td></tr>
</table>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading