返回一个匹配特定 ID的元素.
语法
element = document.getElementById(id);
参数
element是一个Element 对象。如果当前文档中拥有特定ID的元素不存在则返回null.id是大小写敏感的字符串,代表了所要查找的元素的唯一ID.
示例
<!DOCTYPE html>
<html>
<head>
<title>getElementById example</title>
<script>
function changeColor(newColor) {
var elem = document.getElementById("para1");
elem.style.color = newColor;
}
</script>
</head>
<body>
<p id="para1">Some text here</p>
<button onclick="changeColor('blue');">blue</button>
<button onclick="changeColor('red');">red</button>
</body>
</html>
注意
新手要注意方法名中 'Id' 的拼写——'getElementByID' 是没有作用的。许多人会忽视这个错误。
如果没有查找到对应的元素,方法会返回null。注意ID参数是大小写敏感的,所以document.getElementById("Main")无法获取到元素<div id="main">,因为'M'和'm'是不一样的。
getElementById方法不会搜索不在文档中的元素。当创建一个元素,并且分配ID后,你必须要使用insertBefore或其他类似的方法把元素插入到文档中之后才能使用 getElementById 获取到:
var element = document.createElement("div");
element.id = 'testqq';
var el = document.getElementById('testqq'); // el will be null!
非HTML文档(Non-HTML documents)。 DOM的实现必须说明哪个属性是ID类型。只有DTD定义了'id'是ID属性时’id‘才会被认为是ID属性。在 XHTML, XUL或者其他文档中,'id'通常被定义为ID类型的属性。不知道哪个属性是ID类型的实现中,这会返回null结果。
规范
| 规范 | 状态 | 说明 |
|---|---|---|
| Document Object Model (DOM) Level 1 Specification getElementById |
Recommendation | 接口初始定义 |
| Document Object Model (DOM) Level 2 Core Specification getElementById |
Recommendation | 取代DOM 1 |
| Document Object Model (DOM) Level 3 Core Specification getElementById |
Recommendation | 取代DOM 2 |
| DOM getElementById |
Living Standard | 准备取代DOM 3 |
浏览器兼容性
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari (WebKit) |
|---|---|---|---|---|---|
| Basic support | 1.0 | 1.0 (1.7 or earlier) | 5.5 | 7.0 | 1.0 |
| Feature | Android | Firefox Mobile (Gecko) | IE Phone | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|
| Basic support | 1.0 | 1.0 (1.0) | 6.0 | 6.0 | 1.0 |
相关链接
- document reference for other methods and properties you can use to get references to elements in the document.
- document.querySelector() 类似'div.myclass'的元素的选择
- xml:id - has a utility method for allowing getElementById to obtain 'xml:id' in XML documents (such as returned by Ajax calls)