Creating and Removing Elements & Working with Forms in JavaScript DOM

Table of contents
Creating and Removing Elements in JavaScript DOM
JavaScript provides various methods to dynamically create, add, remove, and replace elements in the DOM. These operations help in modifying the structure of a webpage without reloading it.
1. document.createElement()
What It Does:
- Creates a new element in the document but does not insert it into the DOM until explicitly appended.
Syntax:
let newElement = document.createElement("tagname");
Real-Life Examples:
Creating a New Paragraph and Adding It to a Div
<div id="container"></div> <script> let para = document.createElement("p"); para.innerText = "Hello, this is a new paragraph!"; document.getElementById("container").appendChild(para); </script>
Dynamically Adding an Image
<div id="imageContainer"></div> <script> let img = document.createElement("img"); img.src = "https://via.placeholder.com/150"; img.alt = "Placeholder Image"; document.getElementById("imageContainer").appendChild(img); </script>
Creating a Button Inside a Section
<section id="buttons"></section> <script> let button = document.createElement("button"); button.innerText = "Click Me"; document.getElementById("buttons").appendChild(button); </script>
2. appendChild()
What It Does:
- Appends a child element to a parent node.
Syntax:
parentElement.appendChild(childElement);
Real-Life Examples:
Adding a List Item to an Unordered List
<ul id="list"></ul> <script> let listItem = document.createElement("li"); listItem.innerText = "New Item"; document.getElementById("list").appendChild(listItem); </script>
Adding a New Option to a Select Dropdown
<select id="dropdown"></select> <script> let option = document.createElement("option"); option.value = "new"; option.innerText = "New Option"; document.getElementById("dropdown").appendChild(option); </script>
Appending a New Div to a Section
<section id="container"></section> <script> let newDiv = document.createElement("div"); newDiv.innerText = "This is a new div"; document.getElementById("container").appendChild(newDiv); </script>
3. removeChild()
What It Does:
- Removes a child element from its parent.
Syntax:
parentElement.removeChild(childElement);
Real-Life Examples:
Removing a Specific List Item
<ul id="list"> <li id="item1">Item 1</li> </ul> <button onclick="removeItem()">Remove</button> <script> function removeItem() { let item = document.getElementById("item1"); item.parentNode.removeChild(item); } </script>
Deleting a Button When Clicked
<button id="deleteBtn">Delete Me</button> <script> document.getElementById("deleteBtn").addEventListener("click", function() { this.parentNode.removeChild(this); }); </script>
Removing an Image on Click
<img id="img" src="https://via.placeholder.com/150" alt="Sample Image"> <button onclick="removeImg()">Remove Image</button> <script> function removeImg() { let img = document.getElementById("img"); img.parentNode.removeChild(img); } </script>
4. replaceChild()
What It Does:
- Replaces an existing child element with a new element.
Syntax:
parentElement.replaceChild(newChild, oldChild);
Real-Life Examples:
Replacing an Old Paragraph with a New One
<div id="container"> <p id="old">Old Paragraph</p> </div> <script> let newPara = document.createElement("p"); newPara.innerText = "New Paragraph"; let oldPara = document.getElementById("old"); document.getElementById("container").replaceChild(newPara, oldPara); </script>
Replacing a Button with a Link
<button id="btn">Click Me</button> <script> let link = document.createElement("a"); link.href = "https://example.com"; link.innerText = "Go to Example"; let button = document.getElementById("btn"); button.parentNode.replaceChild(link, button); </script>
Replacing an Image with a Paragraph
<img id="image" src="https://via.placeholder.com/150" alt="Image"> <script> let newText = document.createElement("p"); newText.innerText = "This image has been replaced."; let image = document.getElementById("image"); image.parentNode.replaceChild(newText, image); </script>
5. insertBefore()
What It Does:
- Inserts a new child before a specified existing child.
Syntax:
parentElement.insertBefore(newChild, referenceChild);
Real-Life Examples:
Inserting an Item Before Another in a List
<ul id="list"> <li id="item2">Item 2</li> </ul> <script> let newItem = document.createElement("li"); newItem.innerText = "Item 1"; let list = document.getElementById("list"); list.insertBefore(newItem, document.getElementById("item2")); </script>
Inserting a Heading Before a Paragraph
<p id="text">This is a paragraph.</p> <script> let heading = document.createElement("h2"); heading.innerText = "This is a Heading"; document.body.insertBefore(heading, document.getElementById("text")); </script>
Adding a Button Before an Input Field
<input type="text" id="name"> <script> let button = document.createElement("button"); button.innerText = "Submit"; document.body.insertBefore(button, document.getElementById("name")); </script>
Conclusion
These methods are essential for dynamically modifying web pages, enabling interactivity and better user experience. 🚀
Working with Forms in JavaScript DOM
Forms are essential for collecting user inputs on websites. JavaScript provides various methods to access form elements, handle submissions, and validate input fields efficiently.
1. Accessing Form Elements (document.forms
)
What It Does:
The
document.forms
property allows access to all forms in a document.Each form can be accessed using its name, ID, or index.
Syntax:
let form = document.forms["formName"]; // Accessing form by name
let formById = document.getElementById("formId"); // Accessing form by ID
Real-Life Examples:
Accessing a Form and Its Input Fields
<form name="loginForm"> <input type="text" name="username" placeholder="Enter Username"> <input type="password" name="password" placeholder="Enter Password"> </form> <script> let form = document.forms["loginForm"]; console.log(form.username.value); // Access username field </script>
Getting Form Elements Using
document.getElementById
<form id="signupForm"> <input type="email" id="email" placeholder="Enter Email"> </form> <script> let emailField = document.getElementById("email"); console.log(emailField.value); // Access email input </script>
Iterating Through Form Elements
<form id="myForm"> <input type="text" name="name"> <input type="email" name="email"> </form> <script> let form = document.getElementById("myForm"); for (let i = 0; i < form.elements.length; i++) { console.log(form.elements[i].name); // Logs all input names } </script>
2. Handling Form Submissions
What It Does:
Prevents page refresh.
Collects and processes form data.
Syntax:
document.getElementById("formId").addEventListener("submit", function(event) {
event.preventDefault();
// Process form data
});
Real-Life Examples:
Preventing Default Form Submission
<form id="loginForm"> <input type="text" id="username" required> <button type="submit">Login</button> </form> <script> document.getElementById("loginForm").addEventListener("submit", function(event) { event.preventDefault(); alert("Form submitted without page reload!"); }); </script>
Storing Form Data in Local Storage
<form id="saveForm"> <input type="text" id="name" placeholder="Enter Name"> <button type="submit">Save</button> </form> <script> document.getElementById("saveForm").addEventListener("submit", function(event) { event.preventDefault(); let name = document.getElementById("name").value; localStorage.setItem("userName", name); alert("Name saved successfully!"); }); </script>
Sending Form Data to Server Using Fetch API
<form id="contactForm"> <input type="text" id="fullName" placeholder="Full Name"> <button type="submit">Send</button> </form> <script> document.getElementById("contactForm").addEventListener("submit", function(event) { event.preventDefault(); let fullName = document.getElementById("fullName").value; fetch("server.php", { method: "POST", body: JSON.stringify({ name: fullName }), }).then(response => alert("Data Sent Successfully!")); }); </script>
3. Validating Input Fields
What It Does:
Ensures that users enter correct data before submitting the form.
Provides feedback if inputs are invalid.
Syntax:
if (input.value === "") {
alert("Field cannot be empty!");
}
Real-Life Examples:
Checking for Empty Fields Before Submission
<form id="validateForm"> <input type="text" id="userInput" placeholder="Enter Text"> <button type="submit">Submit</button> </form> <script> document.getElementById("validateForm").addEventListener("submit", function(event) { let input = document.getElementById("userInput").value; if (input === "") { alert("Field cannot be empty!"); event.preventDefault(); } }); </script>
Validating Email Format
<form id="emailForm"> <input type="email" id="emailInput" placeholder="Enter Email"> <button type="submit">Submit</button> </form> <script> document.getElementById("emailForm").addEventListener("submit", function(event) { let email = document.getElementById("emailInput").value; let pattern = /^[^ ]+@[^ ]+\.[a-z]{2,3}$/; if (!email.match(pattern)) { alert("Enter a valid email!"); event.preventDefault(); } }); </script>
Ensuring Password Strength
<form id="passwordForm"> <input type="password" id="passwordInput" placeholder="Enter Password"> <button type="submit">Submit</button> </form> <script> document.getElementById("passwordForm").addEventListener("submit", function(event) { let password = document.getElementById("passwordInput").value; if (password.length < 6) { alert("Password must be at least 6 characters long!"); event.preventDefault(); } }); </script>
Conclusion
JavaScript allows easy access to form elements using
document.forms
.Handling form submissions properly prevents unnecessary page reloads.
Validating inputs ensures proper data entry, leading to better user experience.
Mastering these concepts helps in building interactive and secure web applications. 🚀
Subscribe to my newsletter
Read articles from Payal Porwal directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Payal Porwal
Payal Porwal
Hi there, tech enthusiasts! I'm a passionate Software Developer driven by a love for continuous learning and innovation. I thrive on exploring new tools and technologies, pushing boundaries, and finding creative solutions to complex problems. What You'll Find Here On my Hashnode blog, I share: 🚀 In-depth explorations of emerging technologies 💡 Practical tutorials and how-to guides 🔧Insights on software development best practices 🚀Reviews of the latest tools and frameworks 💡 Personal experiences from real-world projects. Join me as we bridge imagination and implementation in the tech world. Whether you're a seasoned pro or just starting out, there's always something new to discover! Let’s connect and grow together! 🌟