document.getElementById(“selAge”) Vs document.myForms.selAge

后端 未结 4 1988
予麋鹿
予麋鹿 2020-12-22 04:05

What is difference between

document.getElementById(“selAge”) 
document.myForms.selAge

When to use which?

相关标签:
4条回答
  • 2020-12-22 04:48

    They are two different paths to the same goal, which one you use depends on your preference. Personally I would use document.getElementById(“selAge”) because if the structure of your HTML changes then it would still work.

    0 讨论(0)
  • 2020-12-22 04:48

    document.myForms.selAge is part of the DOM specification and so should not be unnecessarily avoided in favour of getElementById. Use whatever is easier.

    0 讨论(0)
  • 2020-12-22 04:51

    The second one is an absolute no-no! It first finds an element with id/name "myForms" and gets its child, with id/name "selAge". The first one finds any element with the id "selAge". Always use the first one ... because, someone, in the future may decide to put "myForms" into a div. Then you're in a fix.

    0 讨论(0)
  • 2020-12-22 05:02

    document.getElementById() is the recommended way to get reference of elements. It's easier to use and also would not require any changes if you decide to change the Form name or Id. However, as it traverses the entire DOM tree, it is usually slower than the document.forms notation of referencing objects, so take this into account when doing a lot of such look-ups.

    document.forms is also harder to use, as you need you to know the entire path to the object beginning from the document element.

    0 讨论(0)
提交回复
热议问题