Phương thức insertAdjacentElement() trong HTML DOM chèn một phần tử vào vị trí được chỉ định tương đối với một nút (node) tham chiếu.
Cú pháp
node.insertAdjacentElement("positionString", element)
Các chuỗi vị trí (positionString)
| positionString | Mô tả |
|---|---|
| afterbegin | Chèn phần tử sau phần tử mở đầu của nút tham chiếu (bên trong, đầu tiên). |
| afterend | Chèn phần tử sau nút tham chiếu (bên ngoài, ngay sau nút). |
| beforebegin | Chèn phần tử trước nút tham chiếu (bên ngoài, ngay trước nút). |
| beforeend | Chèn phần tử trước phần tử kết thúc của nút tham chiếu (bên trong, cuối cùng). |
Ví dụ
Ví dụ minh họa phương thức insertAdjacentElement():
<!DOCTYPE html> <html> <head> <title>insertAdjacentElement()</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>insertAdjacentElement()</legend> <h1>Gia phả gia đình</h1> <span id="Father">Cha --></span> <span id="GrandFather">Ông --></span> <span id="Myself">Tôi</span> <input type="button" onclick="rectifyTree()" value="Sửa gia phả"> </fieldset> </form> <script> function rectifyTree() { var FSpan = document.getElementById("Father"); var GFSpan = document.getElementById("GrandFather"); GFSpan.insertAdjacentElement("afterend", FSpan); } </script> </body> </html>
Kết quả
Trước khi nhấn nút 'Sửa gia phả':

Sau khi nhấn nút 'Sửa gia phả':
