Phương thức insertAdjacentHTML() trong HTML DOM chèn chuỗi văn bản dưới dạng HTML tại một vị trí được chỉ định.
Cú pháp
Gọi insertAdjacentHTML() với tham số positionString và mã HTML:
node.insertAdjacentHTML("positionString", "htmlString")
Các chuỗi vị trí (positionString)
| positionString | Mô tả |
|---|---|
| afterbegin | Chèn htmlString sau phần mở đầu của nút phần tử |
| afterend | Chèn htmlString sau nút phần tử |
| beforebegin | Chèn htmlString trước nút phần tử |
| beforeend | Chèn htmlString trước phần kết thúc của nút phần tử |
Chuỗi HTML (htmlString)
Và htmlString có thể là:
| positionString | <span>new span</span> hoặc <p>Đây là đoạn văn mới</p> hoặc bất kỳ mã HTML hợp lệ nào khác |
Ví dụ
Ví dụ minh họa phương thức insertAdjacentHTML():
<!DOCTYPE html> <html> <head> <title>insertAdjacentHTML()</title> <style> form { width:70%; margin: 0 auto; text-align: center; } * { padding: 2px; margin:5px; } input[type="button"] { border-radius: 10px; } </style> </head> <body> <form> <fieldset> <legend>insertAdjacentHTML()</legend> <h1>Gia phả gia đình</h1> <span id="GrandFather">Ông --></span> <span id="Father">Cha --></span> <span id="Myself">Tôi</span> <input type="button" onclick="rectifyTree()" value="Con trai chào đời"> </fieldset> </form> <script> function rectifyTree() { var MSpan = document.getElementById("Myself"); MSpan.insertAdjacentHTML("afterend", "<span id='Son'>-->Con</span>"); } </script> </body> </html>
Kết quả
Trước khi nhấn nút 'Con trai chào đời':

Sau khi nhấn nút 'Con trai chào đời':
