Search code examples
javascriptjqueryhtmlasp.nettabindex

How to set tabindex for elements on webpage with similar class using jquery


I have multiple elements with anchor tag as below, I am trying to set tabindex only to elements with the anchor tag. Below is the code:

<ul class="level1 static" tabindex="0" role="menu" style="position: relative; width: auto; float: left;">

        <li role="menuitem" class="static" style="position: relative;">
        <a class="level1 static" >program details<span class="visuallyhidden">(Current page)</span></a>
</ul>

Thanks in Advance!


Solution

  • Simple, with $("a").attr('tabindex', 0); you will add/set tabindex="0" to all a element.

    (NOTE: make sure the above code run after all your <a> element are loaded, for dynamic added <a> element just call it again after the new <a> element loaded.)

    tabindex

    The tabindex attribute is versatile, and it has the capacity to improve or destroy usability for keyboard-only users. When you think about using the tabindex attribute, keep these things in mind:

    Use tabindex=0 to include an element in the natural tab order of the content, but remember that an element that is focusable by default may be an easier option than a custom control

    Use tabindex=-1 to give an element programmatic focus, but exclude it from the tab order of the content

    Avoid using tabindex=1+.

    REF: https://www.paciellogroup.com/blog/2014/08/using-the-tabindex-attribute/

    //$("a").attr('tabindex', 0);
    
    
    $("li.static").each(function(index, elm) {
      $($(elm).find('a')).attr('tabindex', 0);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <ul class="level1 static" tabindex="0" role="menu" style="position: relative; width: auto; float: left;">
    
      <li role="menuitem" class="static" style="position: relative;">
        <a class="level1 static">program details<span class="visuallyhidden">(Current page)1</span></a><br>
      </li>
      <li role="menuitem" class="static" style="position: relative;">
        <a class="level1 static">program details<span class="visuallyhidden">(Current page)2</span></a><br>
      </li>
      <li role="menuitem" class="static" style="position: relative;">
        <a class="level1 static">program details<span class="visuallyhidden">(Current page)3</span></a><br>
      </li>
    
    </ul>