Phương pháp HTML DOM Element insertAdjacentText()

Định nghĩa và cách sử dụng

insertAdjacentText() Phương pháp chèn văn bản vào vị trí đã chỉ định.

Vị trí hợp lệ:

Giá trị Mô tả
afterbegin Sau khi phần tử bắt đầu (phần tử con đầu tiên).
afterend Sau phần tử.
beforebegin Trước phần tử.
beforeend Trước khi phần tử kết thúc (phần tử con cuối cùng).

Mô hình

Ví dụ 1

Chèn văn bản sau phần tử tiêu đề:

const h2 = document.getElementById("myH2");
let text = "My inserted text";
h2.insertAdjacentText("afterend", text);

Thử ngay

Ví dụ 2

Sử dụng "afterbegin":

const h2 = document.getElementById("myH2");
let text = "My inserted text";
h2.insertAdjacentText("afterbegin", text);

Thử ngay

Ví dụ 3

Sử dụng "beforebegin":

h2.insertAdjacentText("beforebegin", text);

Thử ngay

Ví dụ 4

Sử dụng "beforeend":

h2.insertAdjacentText("beforeend", text);

Thử ngay

Cú pháp

element.insertAdjacentText(position, text)

hoặc

node.insertAdjacentText(position, text)

Tham số

Tham số Mô tả
position

Phải có. Vị trí tương đối với phần tử:

  • afterbegin
  • afterend
  • beforebegin
  • beforeend
text Văn bản cần chèn.

Trình duyệt hỗ trợ

Tất cả các trình duyệt đều hỗ trợ element.insertAjacentText()

Chrome IE Edge Firefox Safari Opera
Chrome IE Edge Firefox Safari Opera
Hỗ trợ Hỗ trợ Hỗ trợ Hỗ trợ Hỗ trợ Hỗ trợ