How do I set the focus to the first input element in an HTML form independent from the id?

前端 未结 17 1862
遇见更好的自我
遇见更好的自我 2020-12-08 01:33

Is there a simple way to set the focus (input cursor) of a web page on the first input element (textbox, dropdownlist, ...) on loading the

17条回答
  •  自闭症患者
    2020-12-08 02:12

    Without third party libs, use something like

      const inputElements = parentElement.getElementsByTagName('input')
      if (inputChilds.length > 0) {
        inputChilds.item(0).focus();
      }
    

    Make sure you consider all form element tags, rule out hidden/disabled ones like in other answers and so on..

提交回复
热议问题