Rabia Rana Khan
Rabia Rana Khan

Reputation: 202

How to select the last cell from table which is not null, using JQuery

I have a table with following rows and cells:

<table id='table1'>
  <tr id='row1'>
    <th>index</th>
    <th>Product</th>
    <th>Description</th>
  </tr>
  <tr id='row2' name='row'>
    <td name='index'>1</td>
    <td name='product'>Apples</td>
    <td name='description'>fruits</td>
  </tr>
  <tr id='row3' name='row'>
    <td name='index'>2</td>
    <td name='product'>Bananas</td>
    <td name='description'>fruits</td>
  </tr>
  <tr id='row4' name='row'>
    <td name='index'>3</td>
    <td name='product'>Carrots</td>
    <td name='description'>vegetables</td>
  </tr>
  <tr id='row5' name='row'>
    <td name='index'></td>
    <td name='product'></td>
    <td name='description'></td>
  </tr>
</table>

I need to select the value for the last td with name='index' which is not null. Anyone has any idea how can this be done.

Upvotes: 2

Views: 1884

Answers (2)

ZeroBased_IX
ZeroBased_IX

Reputation: 2727

For purely educational purposes, here is a non jQuery version:

function getLastNonEmptyCell(tableSelector) {
  //Find parent table by selector
  var table = document.querySelector(tableSelector)
  //Return null if we can't find the table
  if(!table){
    return null;
  }
  var cells = table.querySelectorAll("td")
  var lastNonEmptyCell = null;
  //Iterate each cell in the table
  //We can just overwrite lastNonEmptyCell since it's a synchronous operation and the return value will be the lowest item in the DOM
  cells.forEach(function(cell) {
    //!! is used so it's so if it is not null, undefined, "", 0, false
    //This could be changed so it's just cell.innerText.trim() !== ""
    if (!!cell.innerText) {
      lastNonEmptyCell = cell;
    }
  })

  return lastNonEmptyCell;
}

var cell = getLastNonEmptyCell("#table1")

Edit

As @squint suggested this can be done much more succintly:

function lastNonEmptyCell(tableSelector) {
  //Since we want the last cell that has content, we get the last-child where it's not empty. This returns the last row.
  var row = document.querySelectorAll(tableSelector + " td:not(:empty):last-child")
  //Just grabbing the last cell using the index
  return row[row.length - 1]
}

Upvotes: 2

Alex C
Alex C

Reputation: 153

Use the following selector :

$('td[name=index]:not(:empty):last')

Upvotes: 6

Related Questions