Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Javascript

โปรแกรม JavaScript เพื่ออัปเดต DOM


ต่อไปนี้เป็นรหัสสำหรับอัปเดต DOM ใน JavaScript -

ตัวอย่าง

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 20px;
      font-weight: 500;
      color: rebeccapurple;
   }
</style>
</head>
<body>
<h1>Update DOM JavaScript</h1>
<div style="color: green;" class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to create a new element</h3>
<script>
   let resEle = document.querySelector(".result");
   let heading = document.createElement("h3");
   document.querySelector(".Btn").addEventListener("click", () => {
      let headingText = document.createTextNode("This is a random heading");
      heading.appendChild(headingText);
      resEle.appendChild(heading);
   });
</script>
</body>
</html>

ผลลัพธ์

รหัสข้างต้นจะสร้างผลลัพธ์ต่อไปนี้ -

โปรแกรม JavaScript เพื่ออัปเดต DOM

เมื่อคลิกปุ่ม 'คลิกที่นี่' -

โปรแกรม JavaScript เพื่ออัปเดต DOM