JavaScript cung cấp insertAdjacentHTML() chèn text dạng HTML vào vị trí chỉ định. 4 vị trí hợp lệ:
afterbeginafterendbeforebeginbeforeend
Ví dụ 1: afterend - Sau element
<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>
Kết quả
<h3>Header</h3> Tutorix is the best e-learning platform
Ví dụ 2: beforeend - Trước end tag
<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>
Kết quả
<h3>Header</h3> <h3>Tutorix is the best e-learning platform</h3>
Ưu điểm: Nhanh hơn innerHTML (không parse lại toàn bộ), an toàn hơn document.write. Có thêm insertAdjacentText() chèn text thuần túy (auto escape HTML).