sortof sortof - 2 years ago 115
jQuery Question

How to select a specific tr based on attribute value

i got this table html:

<table id="mytable">
<tr role="row">
<th aria-controls="dog"></th>
<th aria-controls="cat"></th>
<th aria-controls="fish"></th>

and i want to select the th where the attribute is "dog".

i try this :


what is a god way to do it?

if i can i avoid looping on all the tr it will be even better.

thanks :)

Answer Source

You can select elements by what an attribute is equal to like this:

var element = $('th[aria-controls="dog"]')

More info on attribute equals selector here:

As a side not the th is not even necessary. You can simply select all elements with that attribute regardless of its value too like this:

var element = $('[aria-controls]')

Many ways of using this selector. You can even find elements with that attribute that start, end or contain the value.

Starts with: var element = $('[aria-controls|="dog"]') ex: dogggg

Ends with: var element = $('[aria-controls$="dog"]') ex: adog

Contains with: var element = $('[aria-controls*="dog"]') ex: bdogb

Not equal: var element = $('[aria-controls!="dog"]') ex: cat

More info on attribute selectors in general here:

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