user9402741
user9402741

Reputation:

Disable tabbing between links but inputs

I am trying to disable tabbing between links with pure Javascript or with a simple css class that will affect the entire website:

Here is what i try to do

document.getElementsByTagName("a")[0].setAttribute("tabindex", "-1");

This is how it can be achieved with jquery:

$('a').attr('tabindex', '-1');

Upvotes: 0

Views: 109

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370699

jQuery's $('a').attr:

sets one or more attributes for every matched element.

If you do

document.getElementsByTagName("a")[0].setAttribute

As you can see by the [0] there, you're only setting the attribute of one element. You need to loop through all elements instead:

document.querySelectorAll('a').forEach(
  a => a.setAttribute('tabindex', '-1')
);
<input placeholder="click on me, then press tab">
<a href="example.com">link</a>
<a href="example.com">link</a>
<a href="example.com">link</a>

(Compare to, with no Javascript at all:)

<input placeholder="click on me, then press tab">
<a href="example.com">link</a>
<a href="example.com">link</a>
<a href="example.com">link</a>

For old browsers that don't support NodeList.forEach, use the polyfill, or call the forEach like this instead:

Array.prototype.forEach.call(
  document.querySelectorAll('a'),
  function(a){ a.setAttribute('tabindex', '-1'); }
);

Upvotes: 2

Related Questions