Beispiel:JS-DOM-element-entfernen.html

Aus SELFHTML-Wiki
Wechseln zu: Navigation, Suche
<!DOCTYPE html>
<html lang="de">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>parentNode.removeChild</title>
  <link rel="stylesheet" media="screen" href="./Beispiel:SELFHTML-Beispiel-Grundlayout.css">    
  <style>
.hint {
  color: #c82f04; font-weight: bold;
}

aside,
div {
	background: #e6f2f7;
  border: 2px dotted #337599;	
	padding: 1em;
}

h2,
h3,
h4 {
background-color: #fffbf0;
  border: 2px dotted #e7c157;
	margin-top: 5px;
	max-width: 90%; 
}
img {
 	float: right;
	clear: right;
	width: 10em;
}

main { 
	border: thin dotted;
	padding: 1em;
	grid-row: 2 /5;
}

body { 
	display: grid;
	grid-template-columns: 1fr 12em;
	gap: 1em;
	max-width: 60em;
}

h1 {
	grid-column: 1 / -1;
}
	
    #output {
      margin-top: 1em;
      padding: 1em;
      border: thin solid #c82f04;
      background-color: #fed8cd;
    }
    #output pre {
      margin: 0;
			font-family: monospace;
      white-space: pre-wrap;
    }
  </style>
</head>
<body>
  <h1>Mach das weg!  - <code>parentNode.removeChild</code></h1>
  <main>
  <p class="hint">Klick' auf jedes Element, um es zu löschen!</p>	

<p id="derText">Text mit <strong>fettem Text</strong> und <u>unterstrichenem Text</u> <img src="https://wiki.selfhtml.org/images/4/45/SELF-Logo.svg" alt="Self-Logo"></p>
	<h2>Ober-Überschrift</h2>

	<h3>Unter-Überschrift</h3>
	<ul>
		<li>Pizza</li>
		<li>Pasta</li>
		<li>Prosciutto</li>
	</ul>
	<h3>Unter-Überschrift</h3>
	<ol>
		<li>Pizza</li>
		<li>Pasta</li>
		<li>Prosciutto</li>
	</ol>
  </main>
   <div id="bar">
		<h3>Überschrift-Div</h3>
		<p>Absatz-Div</p>
	</div>
	<aside>
		<h3>Überschrift-aside</h3>
		<p>Absatz-aside</p>
	</aside> 
  <div id="output"><strong>Output:</strong> <pre></pre></div>

  <script>
document.addEventListener('DOMContentLoaded', function () {
	document.body.addEventListener('click', removeElement);

	function removeElement(e) {
		let elem = e.target;
		const main = document.querySelector('main');
		if (main != elem) {
			elem.parentNode.removeChild(elem);
			return false;
		}
	}
});

  </script>
</body>
</html>