如何在通过javascript知道td的href包含特定文本的情况下找到表行id

How to find table row id when knowing href of td contains specific text by javascript

本文关键字:情况下 文本 id 包含特 href javascript td 知道      更新时间:2023-09-26

我有以下格式的行:

   <tr id="_ctl0_viewCompanies_companyRepeater_myresultsRow1_13" class="DGAlternatingItemStyle">
    <td style="padding:0.5em;">
<a style="color: #8B0000; font-size: 1em; font-weight:normal;" href="http://mylinkhere?itemid=12367" target="_blank">some name text</a>
</td>

我知道href中的这个部分itemid=12367是唯一的,我怎么能找到tr的id包含那个项目id?(结果应为:_ctl0_viewCompanies_companyRepeater_myresultsRow1_13)我尝试过的:

 function getAllElementsWithAttribute()
{
  var matchingElements = [];
  var allElements = document.getElementsByTagName('*');
  for (var i = 0, n = allElements.length; i < n; i++)
  {
    if (allElements[i].getAttribute("href"))
    {
      // Element exists with attribute. Add to array.
      matchingElements.push(allElements[i]);
    }
  }
  alert ( matchingElements );
}

但我不知道接下来还能做什么。

您可以使用属性contains选择器来获取具有href的唯一部分的锚点,然后获取最接近的TR

$('a[href*="itemid=12367"]').closest('tr').prop('id')

FIDDLE

使用jQuery以选择器结束

 $('a[href$="itemid=12367"]').closest('tr').attr('id')

演示

相关文章: