Manipulation des DOM
DOM Objekte erzeugen + einbinden
| Funktion | Beschreibung |
|---|
| document.createElement(tagName, [optionen]) | Erzeugt ein HTMLELement mit dem Tag tagName |
| .cloneNode([deep]) | Erzeugt eine Kopie des Knoten (und der Kindknoten, wenn deep = true) |
| .appendChild(node) | Fügt node als letzten Kindknoten des Knoten ein (und gibt node zurück) |
| .insertBefore(node, reference) | Fügt node vor dem reference Kindknoten des Knoten ein (und gibt node zurück) |
| .append(node1, node2) | wie appendChild, nur mehrere Kindknoten (oder Strings) auf einmal (ohne Rückgabe) |
JavaScriptlet hallo = document.createElement('p');
hallo.textContent = 'Hallo';
document.body.appendChild(hallo);
let hallo2 = hallo.cloneNode();
hallo2.textContent = 'Hallo2';
hallo2.style.color = 'green'; // style meist besser über class ändern
document.body.insertBefore(hallo2, hallo);
DOM Knoten löschen
| Node Methode | Beschreibung |
|---|
| removeChild(node) | Löscht node als Kind des Knoten (und gibt node zurück) |
| replaceChild(replacement, node) | Ersetzt node als Kind des Knoten durch replacement (und gibt node zurück) |
HTML<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8" />
<title>Titel der Seite</title>
</head>
<body>
<p>Text1</p>
<p>Text2</p>
</body>
</html>
JavaScriptdocument.body.removeChild(document.getElementsByTagName('p')[0]);