HTML DOM insertAdjacentHTML () Phương thức
Thí dụ
Chèn một phần tử <p> mới sau phần tử tiêu đề:
var h = document.getElementById("myH2");
h.insertAdjacentHTML("afterend",
"<p>My new paragraph</p>");
Định nghĩa và Cách sử dụng
Phương insertAdjacentHTML()
thức này sẽ chèn một văn bản dưới dạng HTML, vào một vị trí được chỉ định.
Giá trị vị trí pháp lý là:
"afterbegin"
"afterend"
"beforebegin"
"beforeend"
Hỗ trợ trình duyệt
Các số trong bảng chỉ định phiên bản trình duyệt đầu tiên hỗ trợ đầy đủ phương pháp này.
Method | |||||
---|---|---|---|---|---|
insertAdjacentHTML() | 1 | 4 | 8 | 4 | 7 |
Cú pháp
node.insertAdjacentHTML(position, text)
Giá trị tham số
Parameter | Type | Description |
---|---|---|
position | String | Required. A position relative to the element. Legal values: "afterbegin" - After the beginning of the element (as the first child) "afterend" - After the element "beforebegin" - Before the element "beforeend" - Before the end of the element (as the last child) |
text | String | The text you want to insert |
Các ví dụ khác
Thí dụ
Sử dụng giá trị "afterbegin":
h.insertAdjacentHTML("afterbegin", "<span style='color:red'>My span</span>");
Thí dụ
Sử dụng giá trị "beforebegin":
h.insertAdjacentHTML("beforebegin", "<span style='color:red'>My span</span>");
Thí dụ
Sử dụng giá trị "beforeend":
h.insertAdjacentHTML("beforeend", "<span style='color:red'>My span</span>");