ออบเจ็กต์ Article (Article Object)
ออบเจ็กต์ Article ใน HTML DOM แทนอิลิเมนต์ HTML <article> ที่นำมารวมใน HTML5 อิลิเมนต์ <article> ใช้สำหรับเนื้อหาที่เป็นอิสระสมบูรณ์ (self-contained) ในเอกสาร HTML เช่น บทความบล็อก, โพสต์ฟอรัม, คอมเมนต์, หรือ widget ที่สามารถกระจายได้ด้วยตนเอง เป็นส่วนหนึ่งของ semantic tags ที่เพิ่มความหมายให้กับโครงสร้างเอกสาร
ไวยากรณ์ (Syntax)
การสร้างอิลิเมนต์ article
var articleElement = document.createElement("ARTICLE");
ตัวอย่างการใช้งาน
ตัวอย่างด้านล่างแสดงการสร้าง, เข้าถึง และแก้ไขอิลิเมนต์ <article>
<!DOCTYPE html>
<html>
<body>
<h3>ARTICLE HEADING</h3>
<article id="ArticleObj">
<h1>Heading</h1>
<p>Sample Article Text</p>
</article>
<p>Click the below button to change article size and color</p>
<button onclick="ChangeArticle()">CHANGE</button>
<button onclick="AddArticle()">ADD</button>
<script>
function ChangeArticle() {
var x = document.getElementById("ArticleObj");
x.style.color = "green";
x.style.fontSize = "25px";
}
function AddArticle() {
var x = document.createElement("ARTICLE");
x.setAttribute("id", "myArticle");
document.body.appendChild(x);
var heading = document.createElement("H1");
var txt1 = document.createTextNode("Append Article");
heading.appendChild(txt1);
document.getElementById("myArticle").appendChild(heading);
}
</script>
</body>
</html>
ผลลัพธ์
เริ่มต้น: แสดง article เดิมพร้อมปุ่ม CHANGE และ ADD
คลิก CHANGE: article เปลี่ยนสีตัวอักษรเป็นเขียวและขนาด 25px
คลิก ADD: สร้าง article ใหม่พร้อม heading "Append Article" เพิ่มท้าย body
คำอธิบายโค้ด
1. Article เดิม
<article id="ArticleObj"> <h1>Heading</h1> <p>Sample Article Text</p> </article>
2. ปุ่มควบคุม
<button onclick="ChangeArticle()">CHANGE</button> <button onclick="AddArticle()">ADD</button>
3. ฟังก์ชัน ChangeArticle()
function ChangeArticle() {
var x = document.getElementById("ArticleObj");
x.style.color = "green";
x.style.fontSize = "25px";
}
4. ฟังก์ชัน AddArticle()
function AddArticle() {
var x = document.createElement("ARTICLE");
x.setAttribute("id", "myArticle");
document.body.appendChild(x);
var heading = document.createElement("H1");
var txt1 = document.createTextNode("Append Article");
heading.appendChild(txt1);
document.getElementById("myArticle").appendChild(heading);
}
คำอธิบายเพิ่มเติม
<article>ควรมี heading (<h1>-<h6>) เป็นลูกโดยตรง- สามารถซ้อน
<article>ได้ (เช่น คอมเมนต์ภายในบทความ) - ช่วย SEO และ accessibility ให้เข้าใจโครงสร้างเนื้อหา
- ต่างจาก
<section>(กลุ่มเนื้อหาที่เกี่ยวข้อง) และ<div>(container ไม่มีความหมาย)