Claire F
Claire F

Reputation: 1

Adding of attribute before an element by a class as identifier

I want to add an aria-hidden attribute in this certain who have the a.actionSort.

<table class="dataTable" id="resulttable" name="resulttable">
    <thead>
        <tr>
        <th name="bookID" class="sortable"> Book ID</th>
        <th name="bookName" class="sortable"> <a class="actionSort"> Book Name</a></th>
        <th name="category" class="sortable"> Category</th>
        <th name="price" class="sortable"> Price</th>
        </tr>
    </thead>
    <tbody id="resulttable_body">
        <tr>
        <td>1</td>
        <td>Computer Architecture</td>
        <td>Computers</td>
        <td>125.60</td>
        </tr>
        <tr>
        <td>2</td>
        <td>Asp.Net 4 Blue Book</td>
        <td>Programming</td>
        <td>56.00</td>
        </tr>
        <tr>
        <td>3</td>
        <td>Popular Science</td>
        <td>Science</td>
        <td>210.40</td>
        </tr>
    </tbody>
</table>

I tried this script but it always add the aria-hidden true in all

var y = $('.dataTable').find('th').length;
for (var i = 0; i < y; i++) { 
    if ($( ".dataTable th a" ).hasClass( "actionSort" ) === true) {
                  $( ".dataTable th").attr( "aria-hidden", "true" );
        }
}

Upvotes: 0

Views: 30

Answers (2)

epascarello
epascarello

Reputation: 207501

Since you are using jQuery you can do something like

$('.dataTable').find('th a.actionSort')
  .closest('th')
    .attr( "aria-hidden", "true" );

or you can use has

$('.dataTable').find('th:has(a.actionSort)')
  .attr( "aria-hidden", "true" );

to do the loop

var ths = $('.dataTable').find('th');
ths.each(function() {
  var th = $(this);
  var isActive = th.find("a").hasClass('actionSort');
  if (isActive) {
    th.attr( "aria-hidden", "true" );
  }
});

Upvotes: 0

imvain2
imvain2

Reputation: 15847

You can use this to refer to the element. Also I simplified your loop.

$('.dataTable th a.actionSort').each(function(){
    $(this).parent().attr( "aria-hidden", "true" );
});

Upvotes: 1

Related Questions