theglossy1 theglossy1 - 7 months ago 12
Javascript Question

Finding last occurrence of text

I have the following type of table in html, which is generated dynamically by php :

<tr><td>Kiss the Girls</td><td>2016-01-01</td></tr>
<tr><td>Kiss the Girls</td><td>2016-02-05</td></tr>
<tr><td>Along Came a Spider</td><td>2016-01-07</td></tr>
<tr><td>Along Came a Spider</td><td>2016-01-22</td></tr>
<tr><td>Along Came a Spider</td><td>2016-03-31</td></tr>

I would like to be able to have a dynamic display filter that would allow the user to click a box and hide all but the latest version of the manuscript. So it might look like :

<tr><td>Kiss the Girls</td><td>2016-02-05</td></tr>
<tr><td>Along Came a Spider</td><td>2016-03-31</td></tr>

At this point none of the
tags have an id or a class, but I could easily add a class to the first column (e.g.,
<td class='bookTitle'>
). There is only one table on the page and php sorts it by date already. I'm open to jQuery or native JavaScript, though I would think this would be easier with jQuery. Seems like it could be done by just grabbing the last row before it changes names, but I'm not sure how to do that. Any thoughts?


According to 'Seems like it could be done by just grabbing the last row before it changes names', this is what I've come out with:

var rows = $("table tr");
if(rows.length > 0){
  var last = $(rows[0]).find('td')[0].innerText;
  for(var i=1; i<rows.length; i++){
     var row = $(rows[i]);
     var text = row.find('td')[0].innerText;
     if(text === last){
     last = text;
See the Pen Finding last occurrence of text by Tan Li Hau (@tanhauhau) on CodePen.