Zach Smith
Zach Smith

Reputation: 5674

JavaScript focus a particular element with div class, not div id declaration

The following function can focus on an element with an id declaration:

function setFocus() { 
    document.getElementById("focus").focus(); 
} 

But how can one focus on an element with a classname declaration. Use case would be previously in the code where the element we want to focus on is already stored from the dom (i.e., const element = document.querySelectorAll('.a-class-name')[0]) type of scenario?

Upvotes: 1

Views: 8803

Answers (3)

Zach Smith
Zach Smith

Reputation: 5674

element.scrollIntoView(true) will do what you are needing.

Upvotes: 0

Adrian Brand
Adrian Brand

Reputation: 21628

Does the element have a tab index? You cannot focus a non input element unless it has a tab index. Use tabindex="-1" for elements like divs and spans. Then call the .focus() method on the element. -1 will allow you to focus with the focus method but wont get focus when move the focus around with the keyboard and pressing tab.

document.getElementById('btn').addEventListener('click', function() {
  document.querySelectorAll('.focus_me')[0].focus();
});
<span class="focus_me" tabindex="-1">Focus me</span><br>
<button id="btn">Click to focus</button>

Upvotes: 2

Adil Ahmed
Adil Ahmed

Reputation: 435

document.getElementsByClassName('className') would always return multiple elements because conceptually Classes are meant to be applied to multiple elements. If you want only the first element in the DOM with that class, you can select the first element out of the array returned, as you did.

var elements = document.getElementsByClassName('className');
var requiredElement = elements[0];

OR

var requiredElement = document.querySelector('.className');

Then as @j08691 mentioned in the comments use

function setFocus() { 
    requiredElement.focus(); 
}

If the one with getElementById works, then there is no reason for this to not. Happy coding. :)

Upvotes: -1

Related Questions