這裡整理了一些 JavaScript 操作 HTML 的常用程式碼,方便隨時查閱。
document.write(Date());
document.getElementById("p1").innerHTML = "New text!";
document.getElementById("image").src = "https://hovertree.com/hvtimg/201601/lbau8hqb.png";
document.getElementById("p2").style.color = "blue";
<button onclick="displayDate()">點擊這裡</button>
<script>
function displayDate() {
document.getElementById("de").innerHTML = Date();
}
</script>
<p id="de"></p>
<div onmousedown="mDown(this)" onmouseup="mUp(this)"
style="background-color:green; width:120px; height:20px; padding:40px; color:#ffffff;">
把滑鼠移到上面
</div>
<script>
function mDown(obj) {
obj.innerHTML = "謝謝";
obj.style.backgroundColor = "#1ec5e5";
}
function mUp(obj) {
obj.innerHTML = "把滑鼠移到上面";
obj.style.backgroundColor = "green";
}
</script>
var para = document.createElement("p");
var node = document.createTextNode("這是新段落");
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
var child = document.getElementById("p1");
child.parentNode.removeChild(child);