user1314404
user1314404

Reputation: 1295

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

I have rows in this format:

   <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>

I know this part itemid=12367 in href is unique, how could I find the id of tr contains that itemid ? (the result should be: _ctl0_viewCompanies_companyRepeater_myresultsRow1_13 ) What I tried:

 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 );
}

But I not sure what else to do from there.

Upvotes: 1

Views: 1056

Answers (2)

vikrant singh
vikrant singh

Reputation: 2111

Use jQuery ends with selecter

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

DEMO

Upvotes: 2

adeneo
adeneo

Reputation: 318182

You can use the attribute contains selector to get the anchor with that unique part of the href, then get the closest TR

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

FIDDLE

Upvotes: 3

Related Questions