文档对象模型
发布: (2026年4月28日 GMT+8 13:15)
1 分钟阅读
原文: Dev.to
Source: Dev.to
什么是 getElementById()?
它用于通过唯一的 id 属性选择单个 HTML 元素。
如果找到匹配项,则返回一个 Element 对象;否则返回 null。
基本用法
## Hello
let el = document.getElementById("title");
console.log(el);
输出
## Hello
操作选中的元素
let el = document.getElementById("title");
// Change text content
el.textContent = "Hello, JavaScript!";
el.innerText = "Hi!";
// Insert HTML
el.innerHTML = "**How**";
// Style the element
el.style.color = "red";
el.style.backgroundColor = "yellow";
// Style the page background
document.body.style.backgroundColor = "black";
带按钮的完整示例
## Hello
click
let el = document.getElementById("title");
let btn = document.getElementById("btn");
btn.addEventListener("click", () => {
el.innerText = "Welcome!";
});