Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> HTML

Phương thức insertAdjacentText() trong HTML DOM

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)

positionStringMô tả
afterbeginChèn văn bản sau phần mở đầu của nút phần tử
afterendChèn văn bản sau nút phần tử
beforebeginChèn văn bản trước nút phần tử
beforeendChè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':

Phương thức insertAdjacentText() trong HTML DOM

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

Phương thức insertAdjacentText() trong HTML DOM