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
<!DOCTYPE html>
<html>
<body>
<h1>The Document Object</h1>
<h2>The createElement() Method</h2>
<p>Create a p element with some text:</p>
<script>
// Create element:
const para = document.createElement("p");
para.innerText = "This is a paragraph.";
// Append to body:
document.body.appendChild(para);
</script>
</body>
</html>
kode : menghapus elemen
<!DOCTYPE html>
<html>
<body>
<h1>The Element Object</h1>
<h2>The removeChild() Method</h2>
<p>Click "Remove" to remove the first item from the list:</p>
<button onclick="myFunction()">Remove</button>
<ul id="myList">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
<script>
function myFunction() {
const list = document.getElementById("myList");
list.removeChild(list.firstElementChild);
}
</script>
</body>
</html>
kode : menambah elemen
<!DOCTYPE html>
<html>
<body>
<h1>The Element Object</h1>
<h2>The appendChild() Method</h2>
<ul id="myList">
<li>Coffee</li>
<li>Tea</li>
</ul>
<p>Click "Append" to append an item to the end of the list:</p>
<button onclick="myFunction()">Append</button>
<script>
function myFunction() {
// Create an "li" node:
const node = document.createElement("li");
// Create a text node:
const textnode = 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>