HTML DOM ช่วยให้ JavaScript เปลี่ยนรูปแบบขององค์ประกอบ HTML
หากต้องการเปลี่ยนรูปแบบขององค์ประกอบ HTML ให้ใช้ไวยากรณ์นี้:
document.getElementById(id).style.property = new style
ตัวอย่างต่อไปนี้เปลี่ยนรูปแบบขององค์ประกอบ <p>
:
<html>
<body>
<p id="p2">Hello World!</p>
<script>
document.getElementById("p2").style.color = "blue";
</script>
</body>
</html>
ลองด้วยตัวคุณเอง →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript HTML DOM</h2>
<p>Changing the HTML style:</p>
<p id="p1">Hello World!</p>
<p id="p2">Hello World!</p>
<script>
document.getElementById("p2").style.color = "blue";
document.getElementById("p2").style.fontFamily = "Arial";
document.getElementById("p2").style.fontSize = "larger";
</script>
</body>
</html>
HTML DOM ช่วยให้คุณสามารถรันโค้ดเมื่อมีเหตุการณ์เกิดขึ้น
เหตุการณ์จะถูกสร้างขึ้นโดยเบราว์เซอร์เมื่อ "สิ่งที่เกิดขึ้น" กับองค์ประกอบ HTML:
องค์ประกอบถูกคลิก
มีการโหลดหน้าเว็บแล้ว
ช่องป้อนข้อมูลมีการเปลี่ยนแปลง
คุณจะได้เรียนรู้เพิ่มเติมเกี่ยวกับกิจกรรมในบทถัดไปของบทช่วยสอนนี้
ตัวอย่างนี้เปลี่ยนรูปแบบขององค์ประกอบ HTML ด้วย id="id1"
เมื่อ ผู้ใช้คลิกปุ่ม:
<!DOCTYPE html>
<html>
<body>
<h1 id="id1">My Heading 1</h1>
<button type="button"
onclick="document.getElementById('id1').style.color = 'red'">
Click Me!</button>
</body>
</html>
ลองด้วยตัวคุณเอง →
<!DOCTYPE html>
<html>
<body>
<h1 id="id1">My Heading 1</h1>
<button type="button"
onclick="document.getElementById('id1').style.color = 'red'">
Click Me!</button>
</body>
</html>
ทัศนวิสัย
<!DOCTYPE html>
<html>
<body>
<p id="p1">
This is a text.
This is a text.
This is a text.
This is a text.
</p>
<input type="button" value="Hide text" onclick="document.getElementById('p1').style.visibility='hidden'">
<input type="button" value="Show text" onclick="document.getElementById('p1').style.visibility='visible'">
</body>
</html>
สำหรับคุณสมบัติสไตล์ HTML DOM ทั้งหมด โปรดดูที่สมบูรณ์ของเรา การอ้างอิงวัตถุสไตล์ HTML DOM