Phương thức insertAdjacentText() trong HTML DOM chèn chuỗi văn bản tại một vị trí được chỉ định.
Cú pháp
Gọi insertAdjacentText() với tham số positionString và text:
node.insertAdjacentText("positionString", text)
Các chuỗi vị trí (positionString)
| positionString | Mô tả |
|---|---|
| afterbegin | Chèn văn bản sau phần mở đầu của nút phần tử |
| afterend | Chèn văn bản sau nút phần tử |
| beforebegin | Chèn văn bản trước nút phần tử |
| beforeend | Chèn văn bản trước phần kết thúc của nút phần tử |
Ví dụ
Ví dụ minh họa phương thức insertAdjacentText():
<!DOCTYPE html> <html> <head> <title>insertAdjacentText()</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>insertAdjacentText()</legend> <h1>Tổng thống Hồi giáo đầu tiên của Ấn Độ</h1> <h2 id="president">A.P.J Abdul Kalam</h2> <input type="button" onclick="rectifyName()" value="Sửa tên"> </fieldset> </form> <script> function rectifyName() { var presidentH2 = document.getElementById("president"); presidentH2.insertAdjacentText("afterbegin", "TS. "); } </script> </body> </html>
Kết quả
Trước khi nhấn nút 'Sửa tên':

Sau khi nhấn nút 'Sửa tên':
