How to Prevent Tab Indexing on Specific Elements
Solution with the tabindex attribute
The tabindex attribute allows making an element and areas having the element as its DOM anchor be focusable areas, as well as makes it possible to allow or prevent them from being sequentially focusable and define their relative ordering for the sequential focus navigation.
The HTML5 specification supports negative values for tabindex. To prevent tab indexing on specific elements, you can use tabindex="-1". If the value is negative, the user agent will set the tabindex focus flag of the element, but the element should not be reachable with sequential focus navigation.
Example of preventing tab indexing:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<h2>Example of preventing tab indexing</h2>
<form action="/form/submit" method="post">
<input type="text"/>
<input tabindex="-1" placeholder="NoTabIndex"/>
<input type="text"/>
</form>
</body>
</html>
Result
Below, click the first element and try navigating with "Tab" to see the result.
A negative value can be useful when there is off-screen content, which appears on a particular event. Note also that although the user will not be able to focus an element with a negative tabindex with the keyboard but Javascript can do this by using the focus () method.
Example of preventing tab indexing on a <div> element:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
div {
color: purple;
}
</style>
</head>
<body>
<h2>Example of preventing tab indexing</h2>
<p tabindex="1">HTML</p>
<p tabindex="3">CSS</p>
<div tabindex="-1">Prevented tab indexing</div>
<p tabindex="4">Javascript</p>
<p tabindex="2">Git</p>
<p tabindex="5">
Navigate the elements with the "Tab" button.
</p>
</body>
</html>