HTML DOM Document createElement ()
Các ví dụ
Tạo phần tử <p> và nối phần tử đó vào tài liệu:
const para = document.createElement("p");
para.innerText = "This is a paragraph";
document.body.appendChild(para);
Tạo phần tử <p> và nối phần tử đó vào một phần tử:
const para = document.createElement("p");
para.innerHTML = "This is a paragraph.";
document.getElementById("myDIV").appendChild(para);
Thêm ví dụ bên dưới.
Định nghĩa và Cách sử dụng
Phương createElement()
thức tạo một nút phần tử.
Cú pháp
document.createElement(type)
Thông số
Parameter | Description |
type | Required. The type of element to create. |
Giá trị trả lại
Loại | Sự miêu tả |
Nút | Nút phần tử đã tạo. |
Các ví dụ khác
Tạo một nút:
const btn = document.createElement("button");
btn.innerHTML = "Hello Button";
document.body.appendChild(btn);
Hỗ trợ trình duyệt
document.createElement()
là một tính năng DOM Level 1 (1998).
Nó được hỗ trợ đầy đủ trong tất cả các trình duyệt:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9-11 | Yes | Yes | Yes | Yes |