Create & remove HTML element
Simple script for creating HTML element
by jimmzzz
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="styles.css" />
<script src="https://cdn.tailwindcss.com"></script>
<script src="index.js" defer></script>
<title>Create and remove HTML element</title>
</head>
<body>
<button id="createElement" type="button" class="button button--green">
Create element
</button>
<button id="deleteElement" type="button" class="button button--red">
Remove element
</button>
</body>
</html>
CSS
* {
box-sizing: border-box;
}
body {
background: #111827;
font-family: 'Inter', sans-serif;
margin: 0 auto;
padding: 3rem 1.5rem;
max-width: 850px;
}
.title {
margin-bottom: 1rem;
font-size: 3.75rem;
line-height: 1;
font-weight: 800;
color: #ffffff;
}
.subtitle {
font-size: 1.5rem;
line-height: 2rem;
color: #ffffff;
margin-bottom: 12px;
}
.button {
padding-top: 0.625rem;
padding-bottom: 0.625rem;
padding-left: 1.25rem;
padding-right: 1.25rem;
border-radius: 0.5rem;
margin: 1rem 0;
margin-right: 1rem;
width: 100%;
font-size: 0.875rem;
line-height: 1.25rem;
font-weight: 500;
text-align: center;
color: #ffffff;
@media (min-width: 640px) {
width: auto;
}
}
.button--green {
background-color: #2ecc71 !important;
}
.button--green:hover {
background-color: #27ae60 !important;
}
.button--red {
background-color: #e74c3c !important;
}
.button--red:hover {
background-color: #c0392b !important;
}
JavaScript
const createBtnEl = document.getElementById('createElement');
const deleteBtnEl = document.getElementById('deleteElement');
function createElementWithText(tagName, textContent, className) {
const newElement = document.createElement(tagName);
newElement.textContent = textContent;
newElement.setAttribute('class', className);
return newElement;
}
function removeElement(tagName) {
const elementToRemove = document.querySelector(tagName);
if (!elementToRemove) {
console.warn(`No element ${tagName} found`);
return;
}
elementToRemove.remove(elementToRemove);
}
createBtnEl.addEventListener('click', () => {
const newTitle = createElementWithText('h1', 'new Title', 'title');
const newSubtitle = createElementWithText(
'h2',
'This is a subtitle',
'subtitle'
);
document.body.append(newTitle, newSubtitle);
});
deleteBtnEl.addEventListener('click', () => {
removeElement('h1');
removeElement('h2');
});