问题场景:练习写登录页面的时候提交表单,使用document.getElementsByClassName('formname').submit()
结果:不起作用,最后换成document.getElementById('formid').submit()就可以了
查看源码可知,所有的getElementByXX语法里,除了getElementById是返回元素,其他方式皆是返回一个元素集合,因此上述方法使用时需要写为document.getElementsByClassName('formname')[0].submit()
/**
* Returns a reference to the first object with the specified value of the ID attribute.
* @param elementId String that specifies the ID value.
*/
getElementById(elementId: string): HTMLElement | null;
/** Returns a HTMLCollection of the elements in the object on which the method was invoked (a document or an element) that have all the classes given by classNames. The classNames argument is interpreted as a space-separated list of classes. */
getElementsByClassName(classNames: string): HTMLCollectionOf<Element>;
/**
* Gets a collection of objects based on the value of the NAME or ID attribute.
* @param elementName Gets a collection of objects based on the value of the NAME or ID attribute.
*/
getElementsByName(elementName: string): NodeListOf<HTMLElement>;
/**
* Retrieves a collection of objects based on the specified element name.
* @param name Specifies the name of an element.
*/
getElementsByTagName<K extends keyof HTMLElementTagNameMap>(qualifiedName: K): HTMLCollectionOf<HTMLElementTagNameMap[K]>;
getElementsByTagName<K extends keyof SVGElementTagNameMap>(qualifiedName: K): HTMLCollectionOf<SVGElementTagNameMap[K]>;
getElementsByTagName(qualifiedName: string): HTMLCollectionOf<Element>;
/**
* If namespace and localName are "*" returns a HTMLCollection of all descendant elements.
*
* If only namespace is "*" returns a HTMLCollection of all descendant elements whose local name is localName.
*
* If only localName is "*" returns a HTMLCollection of all descendant elements whose namespace is namespace.
*
* Otherwise, returns a HTMLCollection of all descendant elements whose namespace is namespace and local name is localName.
*/
getElementsByTagNameNS(namespaceURI: "http://www.w3.org/1999/xhtml", localName: string): HTMLCollectionOf<HTMLElement>;
getElementsByTagNameNS(namespaceURI: "http://www.w3.org/2000/svg", localName: string): HTMLCollectionOf<SVGElement>;
getElementsByTagNameNS(namespace: string | null, localName: string): HTMLCollectionOf<Element>;
/** Returns an object representing the current selection of the document that is loaded into the object displaying a webpage. */