focus

q6hillz·2022년 4월 17일
0

javascript

목록 보기
47/60

HTMLElement.focus() 상세

The HTMLElement.focus() method sets focus on the specified element, if it can be focused. The focused element is the element which will receive keyboard and similar events by default.

focus 가능한 Class 파생들

There isn't a definite list, it's up to the browser. The only standard we have is DOM Level 2 HTML, according to which the only elements that have a focus() method are HTMLInputElement, HTMLSelectElement, HTMLTextAreaElement and HTMLAnchorElement. This notably omits HTMLButtonElement and HTMLAreaElement.

Try to add the javascript code soon after the input element, so it will execute before the page load complete. In your case autofocus attribute is set to the element but focusing the element which has autofocus by browser is already done. so you setting the value after browser set the focus. when browser trying to set it no attribute is there. try like following code

<input type="text">
<script>
    document.querySelector('input').setAttribute('autofocus', 'autofocus');
</script>

http://jsbin.com/yatugaxe/1/

If you need to do it on button click or something, you need to do it in JavaScript. setting an attribute doesn't mean browser is going to execute it at anytime.

!!중요한건 DOM이 mount 되기도 전에 작성된 스크립트가 먼저 실행되기 때문에 input.focus()가 표현되지 않았던 것이다.

0개의 댓글