sortof sortof - 6 months ago 15
jQuery Question

How to select a specific tr based on attribute value

i got this table html:

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


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

i try this :

$("th").attr("aria-controls"="dog");


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

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: https://api.jquery.com/attribute-equals-selector/

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: https://api.jquery.com/category/selectors/attribute-selectors/