XML DOM getElementById() Method
Definition and Usage
The getElementById() method finds the element with the specified unique ID.
Syntax:
getElementById(elementid)
Parameter | Description |
---|---|
elementid | The value of the id attribute of the element you want to get. |
Return value
Represents the Element node of the document element with the specified id attribute. If no such element is found, it returns null.
Description
This method will retrieve the id attribute value of elementid element node and return it. If no such element is found, it returns null. The value of the id attribute is unique in the document, if this method finds more than one with the specified elementid element node, it will randomly return such an element node, or return null.
This is an important commonly used method, as it provides a convenient way to obtain the Element object representing the specified document element.
注意:该方法的名称以 Id 结尾,不是 ID,不要拼错了。
在 HTML 文档中,该方法总是检索具有指定 id 的属性。可以使用 HTMLDocument.getElementByName() 方法,根据它们的 name 属性中的值来查找 HTML 元素。
在 XML 文档中,这个方法则是使用类型为 id 的任一属性来查找,而不管这个属性的名称是什么。如果 XML 属性的类型是未知的(比如 XML 解析器忽略了或不能定位文档的 DTD),该方法总是返回 null。在客户端 JavaScript 中,这个方法并不经常和 XML 文档一起使用。实际上,getElementById() 最初被定义为 HTMLDocument 接口的一个成员,但是在后来的 2 级 DOM 中移入到 Document 接口中。