Chèn phần tử DOM HTMLAdjacentElement()
Ví dụ
Chèn phần tử span sau tiêu đề:
const span = document.getElementById("mySpan");
const h2 = document.getElementById("myH2");
h2.insertAdjacentElement("afterend", span);
Hãy tự mình thử »Thêm ví dụ dưới đây.
Sự miêu tả
Phương thức insertAdjacentElement()
chèn một phần tử vào một vị trí được chỉ định.
Vị trí pháp lý:
Giá trị | Sự miêu tả |
---|---|
sau khi bắt đầu | Sau phần đầu của phần tử (con đầu tiên) |
sau cùng | Sau phần tử |
trước khi bắt đầu | Trước phần tử |
trước khi kết thúc | Trước phần tử kết thúc (con cuối cùng) |
Cú pháp
element .insertAdjacentElement( position, element )
hoặc
node .insertAdjacentElement( position, element )
Thông số
Parameter | Description |
position | Required. A position relative to the element: afterbegin afterend beforebegin beforeend |
element | The element to insert. |
Thêm ví dụ
Ví dụ
Sử dụng "sau khi bắt đầu":
const span = document.getElementById("mySpan");
const h2 = document.getElementById("myH2");
h2.insertAdjacentElement("afterbegin", span);
Hãy tự mình thử »Ví dụ
Sử dụng "trước khi bắt đầu":
const span = document.getElementById("mySpan");
const h2 = document.getElementById("myH2");
h2.insertAdjacentElement("beforebegin", span);
Hãy tự mình thử »Ví dụ
Sử dụng "trước":
const span = document.getElementById("mySpan");
const h2 = document.getElementById("myH2");
h2.insertAdjacentElement("beforeend", span);
Hãy tự mình thử »Hỗ trợ trình duyệt
element.insertAjacentElement()
được hỗ trợ trong tất cả các trình duyệt:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |