SELF-Treffen in Mannheim 2025
SELFHTML wird 30 Jahre alt! → Veranstaltungs-Ankündigung.
Beispiel:JS-createElement-2.html
Aus SELFHTML-Wiki
<!doctype html>
<html lang="de">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./Beispiel:SELFHTML-Beispiel-Grundlayout.css">
<title>Website-Builder mit createElement()</title>
<style>
form {
background-color: #eee;
padding: 1em;
display: grid;
grid-template-columns: 12em 18em;
gap: 1em;
button {
width: min-content;
}
}
div > h1, h2, h3 {
background-color: #fffbf0;
border-radius: 0 .5em .5em 0;
padding: 0 2em;
}
div > h1 {
border-bottom: medium solid red;
border-left: medium solid red;
}
h2 {
border-bottom: thin solid red;
border-left: medium solid red;
}
aside {
border: thin solid;
border-radius: 1em;
padding: 2em 1em;
color: navy;
background: powderBlue;
float:right;
margin-left: 1em;
}
</style>
</head>
<body><h1>Primitiver Website-Builder mit <code>createElement()</code></h1>
<p>Erzeuge neue Elemente und hänge sie ins DOM.</p>
<form name="Formular" action="">
<label for="elementType">Wähle ein HTML-Element:</label>
<select id="elementType">
<option value="h1">Überschrift 1</option>
<option value="h2">Überschrift 2</option>
<option value="h3">Überschrift 3</option>
<option value="p">Textabsatz</option>
<option value="button">Button</option>
<option value="aside">aside</option>
<option value="hr">Trennlinie</option>
</select>
<label for="content">Elementinhalt hinzufügen</label>
<input type="text" id="content" size="50">
<button type="button" id="add">Hinzufügen</button>
</form>
<div id="result">
</div>
<script>
'use strict';
document.addEventListener('DOMContentLoaded', function () {
const form = document.querySelector('form');
const addButton = document.querySelector('#add');
const elementType = document.querySelector('#elementType');
const contentInput = document.querySelector('#content');
const resultContainer = '#result';
addButton.addEventListener('click', function () {
const element = elementType.value;
const content = contentInput.value.trim();
if (content === '' && element !== 'hr') {
alert('Bitte einen Inhalt für das Element eingeben.');
return;
}
createElement(resultContainer, element, content);
// Eingabefeld wieder leeren
contentInput.value = '';
});
// Helfer-Funktion, um HTML-Elemente zu erzeugen
function createElement(parent, elem, content, attributes = {}) {
const container = document.querySelector(parent);
if (!container) {
console.error(`Parent element "${parent}" not found.`);
return;
}
if (typeof elem !== 'string') {
console.error(`Invalid element type: ${elem}`);
return;
}
const newElm = document.createElement(elem);
newElm.textContent = content;
// Apply optional attributes
for (let [key, value] of Object.entries(attributes)) {
newElm.setAttribute(key, value);
}
container.appendChild(newElm);
}
});
</script>
</body>
</html>