Home > Net >  Find a TR by ID and attribute name with jQuery [duplicate]
Find a TR by ID and attribute name with jQuery [duplicate]

Time:09-29

Hi All I'm working on a web app and I'm trying to find a specific TR using a few criteria.

To keep my code short, here's what it looks like, it's a combination of Razor and HTML but I'm trying to keep this to a minimum....

<tr id="someId" someAttribute="Attribute1" otherAttribute="Attribute2">

My jQuery looks like this:

function GetTRValue(){
   var tr = $('tr[id=someID]:visible');   <-- This works great.

}

This works, and if I look in debugger I can see my attributes.

However what I am trying to achieve is to get this TR using ID and someAttribute - because I want to get the value of otherAttribute

function GetTRValue(){
   debugger;
   var attributeValue = 'Attribute1';
   var tr = $('tr[id=someID] [someAttribute='   attributeValue   ']:visible');   <-- This doesn't work
   console.log(tr);
}

I've also tried to scrap :visible all together (even thought I need to use it)

function GetTRValue(){
   debugger;
   var attributeValue = 'Attribute1';
   var tr = $('tr[id=someID] [someAttribute='   attributeValue   ']');   <-- This doesn't work either
   console.log(tr);
}

What I'm trying to achieve is this:

 function GetTRValue(){
   debugger;
   var attributeValue = 'Attribute1';
   var tr = $('tr[id=someID] [someAttribute='   attributeValue   ']');   <-- This doesn't work either
   //By now I should have the correct tr

   var otherAttribute = tr.attr('otherAttribute'); 
}

Anyone can provide guidance. Thanks.

CodePudding user response:

You had two mistakes:

  1. A misspelled ID (ID/Id)
  2. A space in your selector between attributes, implying a child relationship

var attributeValue = 'Attribute1';
var tr = $('tr[id=someId][someAttribute='   attributeValue   ']:visible');
tr.addClass('hightlight');
.hightlight {
  color: orange;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr id="someId" someAttribute="Attribute1" otherAttribute="Attribute1">
    <td>Row 1</td>
  </tr>
  <tr id="someId" someAttribute="Attribute2" otherAttribute="Attribute2">
    <td>Row 2</td>
  </tr>
</table>

  • Related