Menambah atau Menghapus Elemen HTML Dengan DOM Javascript
menambahkan atau menghapus elemen HTML dengen DOM javascript
Property/Method
Penjelasan
document.createElement(element)
Membuat elemen HTML baru
document.removeChild(element)
Menghapus elemen HTML
document.appendChild(element)
Menambahkan elemen HTML
document.replaceChild(kata baru, kata lama)
Mengubah sebuah kata dalam satu elemen
document.write(text)
Menuliskan teks pada dokumen HTML
kode : membuat elemen
<!DOCTYPEhtml><html><body><h1>The Document Object</h1><h2>The createElement() Method</h2><p>Create a p element with some text:</p><script>// Create element:constpara=document.createElement("p");para.innerText ="This is a paragraph.";// Append to body:document.body.appendChild(para);</script></body></html>
kode : menghapus elemen
<!DOCTYPEhtml><html><body><h1>The Element Object</h1><h2>The removeChild() Method</h2><p>Click "Remove" to remove the first item from the list:</p><buttononclick="myFunction()">Remove</button><ulid="myList"> <li>Coffee</li> <li>Tea</li> <li>Milk</li></ul><script>functionmyFunction() {constlist=document.getElementById("myList");list.removeChild(list.firstElementChild);}</script></body></html>
kode : menambah elemen
<!DOCTYPEhtml><html><body><h1>The Element Object</h1><h2>The appendChild() Method</h2><ulid="myList"> <li>Coffee</li> <li>Tea</li></ul><p>Click "Append" to append an item to the end of the list:</p><buttononclick="myFunction()">Append</button><script>functionmyFunction() {// Create an "li" node:constnode=document.createElement("li");// Create a text node:consttextnode=document.createTextNode("Water");// Append the text node to the "li" node:node.appendChild(textnode);// Append the "li" node to the list:document.getElementById("myList").appendChild(node);}</script></body></html>