0

Всем привет. Есть разметка html типа:

<tr class="">
<td class="date">22:14</td>
<td class="other" style="white-space: nowrap;">Per</td>
<td width="100%">GG: Текст1</td></tr>

<tr class="">
<td class="date">22:17</td>
<td class="other" style="white-space: nowrap;">Per1</td>
<td width="100%">Текст2</td></tr>

<tr class="">
<td class="date">22:20</td>
<td class="other" style="white-space: nowrap;">Per</td>
<td width="100%">GG: Текст3</td></tr>

<tr class="">
<td class="date">22:20</td>
<td class="other" style="white-space: nowrap;">Per</td>
<td width="100%">Текст4</td></tr>

Подскажите, как при помощи js найти значение поля td начинающегося с GG:? Если таких значений несколько, то брать последнее. В данном случае это Текст3. (Их может быть много)

Была попытка начать делать так. Но всё время получаю undefined.

var divs = document.getElementsByTagName("td");

var selectionDiv = document.getElementsByClassName("other");

for(var i = 0; i < divs.length;i++)
//alert(divs[i].val);
{
   if(divs[i].val == selectionDiv)
   {
     var previous = divs[i - 1];
     var next = divs[i + 1];
   }
}

1 ответ 1

3

Например так :

const tds = [...document.getElementsByTagName('td')],
  gg = 'GG: ',
  filtered = tds.filter(e => e.textContent.startsWith(gg)).slice(-1)[0],
  a = filtered && filtered.textContent.substring(gg.length)

console.log(a)
<table>
  <tr class="">
    <td class="date">22:14</td>
    <td class="other" style="white-space: nowrap;">Per</td>
    <td width="100%">GG: Текст1</td>
  </tr>

  <tr class="">
    <td class="date">22:17</td>
    <td class="other" style="white-space: nowrap;">Per1</td>
    <td width="100%">Текст2</td>
  </tr>

  <tr class="">
    <td class="date">22:20</td>
    <td class="other" style="white-space: nowrap;">Per</td>
    <td width="100%">GG: Текст3</td>
  </tr>

  <tr class="">
    <td class="date">22:20</td>
    <td class="other" style="white-space: nowrap;">Per</td>
    <td width="100%">Текст4</td>
  </tr>
</table>

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.