MysticalMamba
MysticalMamba

Reputation: 15

How to remove childNode item before last childNode using jQuery/Vanilla JS?

I am trying to remove the childNode item before the last childNode item.

I currently have a table and I am trying to remove the 2nd last row on the table.

<thead>
    <tr>
        <td></td>
    </tr>

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

    **I want to remove the row below. thead is the parent node and I want to remove the 2nd last row**
     <tr>
        <td></td>
    </tr>

     <tr>
        <td></td>
    </tr>
<thead>

Using jQuery, I tried:

$('thead').children().last().remove();

but this removes the last childNode whereas I want to remove the element before the last element.

Upvotes: 0

Views: 46

Answers (1)

Tomalak
Tomalak

Reputation: 338228

You could do it all with a selector:

$('button').click(function () {
  $('thead > tr:not(:last):last').remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table>
  <thead>
    <tr><td>row 1<td></tr>
    <tr><td>row 2<td></tr>
    <tr><td>row 3<td></tr>
    <tr><td>row 4<td></tr>
  <thead>
<table>

<button>Do it</button>

Upvotes: 1

Related Questions