DOM(Document Object Model)网页加载时,浏览器创建页面的文档对象模型。
-
DOM操作HTML
通过id找到HTML元素,使用属性innerHTML改变HTML内容
<body>
<p id="p1">content1</p>
<button onclick="demo()">点我</button>
<script>
function demo() {
var nv = document.getElementById("p1").innerHTML = "content2";
}
</script>
</body>
通过id找到HTML元素,并修改元素属性
<body>
<a id="a1" href="https://www.baidu.com">链接</a>
<button onclick="demo()">点我</button>
<script>
function demo() {
document.getElementById("a1").href="https://www.yiibai.com";
}
</script>
</body>
-
DOM操作CSS
<body>
<div id="div" class="div"></div>
<button onclick="demo()">点我</button>
<script>
function demo() {
document.getElementById("div").style.backgroundColor="blue";
}
</script>
</body>
-
DOM EventListener:
addEventListener() 添加句柄;removeEventListener() 移除句柄
<body>
<p id="p1">content1</p>
<button id="b1">点我</button>
<script>
var x = document.getElementById("b1");
x.addEventListener("click", f1);
x.addEventListener("click", f2);
x.removeEventListener("click", f1);
function f1() {
alert("content1");
}
function f2() {
alert("content2");
}
</script>
</body>