user2024080
user2024080

Reputation: 5101

How to select the elements by `tabindex`

I would like create a array by selecting the elements by tabindex is it possible? if so what is the correct way to do? I understood that, we need to loop through all element and find the prop declared with tabindex but looking for the right way.

<div class="focusguard" id="focusguard-1" tabindex="0"></div>
<div>
  <input class="user-input" type="text" autofocus tabindex="1">
</div>
<div>
  <ul>
    <li class="first-item" tabindex="2">
      <span>Item 1</span>
    </li>
    <li tabindex="3">Item 2</li>
    <li tabindex="4">Item 3</li>
    <li tabindex="5">Item 4</li>
    <li tabindex="6">Item 5</li>
    <li tabindex="7">Item 6</li>
    <li tabindex="8">Item 7</li>
    <li tabindex="9">Item 8</li>
    <li tabindex="10">Item 9</li>
    <li class="last-item" tabindex="11">Item 10</li>
  </ul>
</div>

How can i create a new array by tabindex -?

Upvotes: 1

Views: 4509

Answers (1)

Mue
Mue

Reputation: 568

You can use querySelectorAll to get all elements with a tabindex on it:

const elmntsWithTabindex = document.querySelectorAll('[tabindex]')

This will give you a NodeList which is not actually an array but can be converted to an array if needed:

const arrayOfElmnts = Array.from(elmntsWithTabindex)

You may, however, not need to convert it to an array because NodeLists already come with some useful methods like forEach():

elmntsWithTabindex.forEach( elmnt => {
  // Do something with that one element
})

Upvotes: 3

Related Questions