Change HTML content
Simple script changing DOM content
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>Changing page content</title>
</head>
<body>
<main>
<h2 class="subtitle">My name is</h2>
<h1 id="name" class="title">Tomáš Hendrych</h1>
<form class="form">
<div class="form-wrapper">
<label for="inputName" class="form-label"> Name </label>
<input
type="text"
id="inputName"
class="form-input"
placeholder="Enter your name and click 'Change name'"
/>
</div>
<button id="changeButton" type="button" class="changeButton">
Change name
</button>
</form>
</main>
</body>
</html>
CSS
* {
box-sizing: border-box;
}
body {
background: #111827;
font-family: 'Inter', sans-serif;
}
main {
margin: 0 auto;
padding: 3rem 1.5rem;
max-width: 650px;
}
.title {
margin-bottom: 1.5rem;
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;
}
.form {
margin: 0 auto;
}
.form-wrapper {
margin-bottom: 1.5rem;
}
.form-label {
display: block;
margin-bottom: 0.5rem;
font-size: 0.875rem;
line-height: 1.25rem;
font-weight: 500;
color: #fff;
}
.form-input {
display: block;
padding: 0.625rem;
border-radius: 0.5rem;
border-width: 1px;
border-color: #d1d5db;
width: 50%;
font-size: 0.875rem;
line-height: 1.25rem;
color: #111827;
background-color: #f9fafb;
}
.changeButton {
padding-top: 0.625rem;
padding-bottom: 0.625rem;
padding-left: 1.25rem;
padding-right: 1.25rem;
border-radius: 0.5rem;
width: 100%;
font-size: 0.875rem;
line-height: 1.25rem;
font-weight: 500;
text-align: center;
color: #ffffff;
background-color: #6d28d9 !important;
@media (min-width: 640px) {
width: auto;
}
}
.changeButton:hover {
background-color: #5b21b6;
}
JavaScript
//1.get element references
const nameEl = document.getElementById('name');
const inputEl = document.getElementById('inputName');
const btnEl = document.getElementById('changeButton');
// 2.add logic triggered when button is clicked
btnEl.addEventListener('click', () => {
const inputValue = inputEl.value;
// 4. prevent user form updating with empty string
if (!inputValue) {
alert('Input is empty, please enter your name');
return;
}
nameEl.textContent = inputValue;
// 3. clearing input
inputEl.value = '';
});