theglossy1 theglossy1 - 2 years ago 75
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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download