Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> HTML

เมธอด appendChild() ใน HTML DOM

เมธอด appendChild()

เมธอด appendChild() ใน HTML DOM ใช้สำหรับสร้างและเพิ่มโหนดข้อความ (text node) หรืออิลิเมนต์เข้าไปที่ตำแหน่งสุดท้ายของรายการโหนดลูก (child nodes) ยังสามารถใช้ย้ายอิลิเมนต์จากตำแหน่งปัจจุบันไปยังตำแหน่งใหม่ได้อีกด้วย ใช้เพิ่มรายการใหม่ในลิสต์ หรือเพิ่มย่อหน้าใหม่ภายในย่อหน้าอื่นได้

ไวยากรณ์ (Syntax)

parentNode.appendChild(node)

พารามิเตอร์: node - ออบเจ็กต์โหนดที่ต้องการเพิ่ม (บังคับ)

ตัวอย่างการใช้งาน

ตัวอย่างด้านล่างแสดงการใช้ appendChild() เพื่อเพิ่มย่อหน้า (<p>) เข้าไปใน <div> ทุกครั้งที่คลิกปุ่ม

<!DOCTYPE html>
<html>
<body>
    <p>Click the button to create a paragraph and append it to the div</p>
    <div id="SampleDIV"> A DIV element </div>
    <button onclick="AppendP()">Append</button>
    <script>
        var x = 1;
        function AppendP() {
            var paragraph = document.createElement("P");
            paragraph.innerHTML = "This is paragraph " + x;
            document.getElementById("SampleDIV").appendChild(paragraph);
            x++;
        }
    </script>
</body>
</html>

ผลลัพธ์

เริ่มต้น: แสดง DIV เดียวและปุ่ม Append

คลิก Append 3 ครั้ง: จะมีย่อหน้าใหม่ 3 ย่อหน้า เพิ่มเข้ามาใน DIV (Paragraph 1, 2, 3)

คำอธิบายโค้ด

  1. Container: <div id="SampleDIV"> เป็นพาเรนท์ที่จะรับ child ใหม่
  2. ปุ่ม: <button onclick="AppendP()">Append</button>
  3. ฟังก์ชัน AppendP():
    var x = 1;
    function AppendP() {
        var paragraph = document.createElement("P");
        paragraph.innerHTML = "This is paragraph " + x;
        document.getElementById("SampleDIV").appendChild(paragraph);
        x++;
    }

คำอธิบายเพิ่มเติม

  • appendChild() vs append(): append() (ใหม่กว่า) รับหลายโหนดและสตริงได้, appendChild() รับเฉพาะโหนดเดียว
  • ย้ายโหนด: ถ้าโหนดมีอยู่ใน DOM แล้ว จะถูกย้ายจากตำแหน่งเดิมไปตำแหน่งใหม่ (ไม่คัดลอก)
  • คืนค่า: คืนโหนดที่เพิ่งเพิ่มเข้าไป (appended node)
  • prepend(): เพิ่มที่ด้านหน้า (first child) แทนที่จะเป็นท้าย
  • before()/after(): เพิ่มก่อน/หลังโหนดอ้างอิง (sibling)