“ getElementByID”如何在JavaScript中工作?
getElementById
的getElementById() 是一个 DOM方法用来返回具有与指定的值的ID属性的元素。这是 HTMLDOM中最常见的方法之一,几乎在每次我们要操作文档中的元素时都使用它。如果不存在具有指定ID的元素,则此方法返回null 。该ID在页面中应该是唯一的。但是,如果存在多个具有指定ID的元素,则它将返回javascript代码中的最后一个元素。
示例1
在以下示例中,存在一个带有内部文本“GetElementById”和一个名为“element”的id的段落标签。使用DOM方法“document.getElementById()”,访问段落标记内的文本,并在输出中显示该值。没有“.innerHtml”,document.getElementById无法读取任何标签的内部文本部分。
<html> <body> <p id="element">GetElementById</p> <script> var s = document.getElementById("element").innerHTML; document.write(s); </script> </body> </html>
输出结果
GetElementById GetElementById
示例2
在下面的示例中,使用DOM方法“getElementById”,我们将原始文本部分“GetElementById”替换为文本“Tutorix”,结果显示在输出中。
<html> <body> <p id="element">GetElementById</p> <script> document.getElementById("element").innerHTML = "Tutorix"; </script> </body> </html>
输出结果
Tutorix