특정 요소에 포커스를 설정하려면 focus() 메서드를 활용하면 됩니다. querySelectorAll()을 사용해 클래스명으로 요소를 선택한 뒤 포커스를 지정하는 방식입니다.
예제 코드
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<span class="TEXT_FOCUS" tabindex="-1"><center>TEXT BOX FOR
FOCUS</center></span><br>
<button id="focusButton">click me to get the tab on focus</button>
<script>
document.getElementById('focusButton').addEventListener('click', function() {
document.querySelectorAll('.TEXT_FOCUS')[0].focus();
});
</script>
</body>
</html>실행 방법
위 프로그램을 실행하려면 파일 이름을 anyName.html(또는 index.html)로 저장한 후, 해당 파일을 마우스 오른쪽 버튼으로 클릭하고 VS Code 편집기에서 Open with Live Server 옵션을 선택하면 됩니다.
실행 결과
페이지를 열면 다음과 같이 버튼이 표시됩니다.

버튼을 클릭하면 .TEXT_FOCUS 클래스를 가진 특정 요소에 포커스가 자동으로 설정됩니다. 실행 결과 스냅샷은 다음과 같습니다.

핵심 포인트 정리
- tabindex="-1": span처럼 기본적으로 포커스를 받을 수 없는 요소도 tabindex 속성을 추가하면 프로그래밍 방식으로 포커스를 설정할 수 있습니다.
- querySelectorAll('.클래스명'): id가 아닌 클래스 기반으로 요소를 선택할 때 사용하며, NodeList 형태로 반환되므로 인덱스([0])로 접근해야 합니다.
- addEventListener('click', ...): 버튼 클릭 이벤트 발생 시 포커스 로직이 실행되도록 합니다.