JavaScript มีเมธอด insertAdjacentHTML() แทรก Text เป็น HTML ในตำแหน่งที่ระบุ ตำแหน่งที่ถูกต้องมีดังนี้
afterbegin
afterend
beforebegin
beforeend
แต่ละตำแหน่งมีความสำคัญเฉพาะตัว มาดูตัวอย่างกัน
ตัวอย่าง
ในตัวอย่างนี้ ใช้ "insertAdjacentHTML()" และตำแหน่ง "afterend" วาง Text ใหม่ติด Header และแสดงผลลัพธ์
<html> <body> <h2 id="H2">Header</h2> <script> var ins = document.getElementById("H2"); ins.insertAdjacentHTML("afterend","<p>Tutorix is the best e-learning platform</p>"); </script> </body> </html>
ผลลัพธ์
<h3>Header</h3> Tutorix is the best e-learning platform
ตัวอย่าง
ในตัวอย่างนี้ ใช้ "insertAdjacentHTML()" และตำแหน่ง "beforeend" วาง Text ใหม่ติด Header และแสดงผลลัพธ์
<html> <body> <h2 id="H2">Header</h2> <script> var ins = document.getElementById("H2"); ins.insertAdjacentHTML("beforeend","<p>Tutorix is the best e-learning platform</p>"); </script> </body> </html>
ผลลัพธ์
<h3>Header</h3> <h3>Tutorix is the best e-learning platform</h3>