今天我偶然发现可以通过元素的id在Javascript中访问DOM元素,例如像这样:
elementid.style.backgroundColor = "blue"
我用一个非常简短的代码片段测试了在IE、Firefox和Chrome中是否可行,结果都可以。
以下是我使用的代码片段:
<html><head>
<script>
function highlight() {
content.style.backgroundColor = "blue";
content.style.color = "white";
}
</script>
</head>
<body>
<div id="content">test content</div>
<div onclick="highlight()">highlight content</div>
</body></html>
我想知道在哪些情况下应该使用document.getElementById('elementid')
(或类似的框架替代方法,如$()),以及直接访问的缺点是什么。
我找不到任何有用的文档。无论哪里都是使用getElementById
或框架方法。