Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to Add and Remove Value Onclick Event in HTML?
Adding and removing values on click events allows you to create dynamic, interactive web pages. This functionality is achieved using JavaScript event handlers that respond to user interactions, enabling you to manipulate DOM elements in real-time when users click on specific elements.
The most common approach involves using JavaScript's addEventListener() method to attach click events and the remove() method to delete elements from the DOM.
Syntax
Following is the syntax for adding click event listeners
element.addEventListener('click', functionName);
Following is the syntax for removing elements
element.remove();
Adding Values on Click Events
The addEventListener() method is JavaScript's primary way to attach event handlers to HTML elements. It accepts the event type ('click') and a callback function that executes when the event occurs. This method allows multiple event handlers on a single element without overwriting existing ones.
Example Adding Dynamic Content
Following example demonstrates how to add new elements to the page when a button is clicked
<!DOCTYPE html>
<html>
<head>
<title>Adding Values on Click</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
<h2>Dynamic Content Example</h2>
<button type="button" onclick="addContent()">Add New Item</button>
<div id="content-area"></div>
<script>
let counter = 1;
function addContent() {
const newItem = document.createElement('p');
newItem.textContent = `Item ${counter} - Added at ${new Date().toLocaleTimeString()}`;
newItem.style.padding = '10px';
newItem.style.backgroundColor = '#f0f0f0';
newItem.style.margin = '5px 0';
newItem.style.borderRadius = '4px';
// Add click event to remove this item when clicked
newItem.addEventListener('click', function() {
this.remove();
});
document.getElementById('content-area').appendChild(newItem);
counter++;
}
</script>
</body>
</html>
Each click on "Add New Item" creates a new paragraph with a timestamp. Clicking on any added item removes it from the page
Dynamic Content Example [Add New Item] Item 1 - Added at 2:30:45 PM Item 2 - Added at 2:30:47 PM (Click on any item to remove it)
Removing Values on Click Events
The remove() method eliminates an element from the DOM completely. This method is called on the element you want to delete and requires no parameters.
Example Removing Specific Elements
Following example shows how to remove predefined elements when buttons are clicked
<!DOCTYPE html>
<html>
<head>
<title>Removing Values on Click</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
<h2>Course List</h2>
<div id="courses">
<p id="html-course">HTML5 - Web Structure Language</p>
<p id="css-course">CSS3 - Web Styling Language</p>
<p id="js-course">JavaScript - Web Programming Language</p>
</div>
<button onclick="removeCourse('html-course')">Remove HTML</button>
<button onclick="removeCourse('css-course')">Remove CSS</button>
<button onclick="removeCourse('js-course')">Remove JavaScript</button>
<script>
function removeCourse(courseId) {
const element = document.getElementById(courseId);
if (element) {
element.remove();
}
}
</script>
</body>
</html>
Each button removes its corresponding course from the list when clicked
Course List HTML5 - Web Structure Language CSS3 - Web Styling Language JavaScript - Web Programming Language [Remove HTML] [Remove CSS] [Remove JavaScript]
Adding and Removing Values Together
Combining both add and remove functionality creates more interactive applications where users can manage content dynamically.
Example Task List Manager
Following example creates a simple task manager where users can add and remove tasks
<!DOCTYPE html>
<html>
<head>
<title>Task List Manager</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
<h2>My Task List</h2>
<input type="text" id="taskInput" placeholder="Enter a new task" style="padding: 8px; width: 200px;">
<button onclick="addTask()">Add Task</button>
<ul id="taskList" style="margin-top: 20px;"></ul>
<script>
function addTask() {
const input = document.getElementById('taskInput');
const taskText = input.value.trim();
if (taskText === '') {
alert('Please enter a task!');
return;
}
const listItem = document.createElement('li');
listItem.style.margin = '8px 0';
listItem.style.padding = '8px';
listItem.style.backgroundColor = '#f8f9fa';
listItem.style.borderRadius = '4px';
const taskSpan = document.createElement('span');
taskSpan.textContent = taskText;
const deleteBtn = document.createElement('button');
deleteBtn.textContent = 'Delete';
deleteBtn.style.marginLeft = '10px';
deleteBtn.style.padding = '4px 8px';
deleteBtn.style.backgroundColor = '#dc3545';
deleteBtn.style.color = 'white';
deleteBtn.style.border = 'none';
deleteBtn.style.borderRadius = '3px';
deleteBtn.style.cursor = 'pointer';
deleteBtn.addEventListener('click', function() {
listItem.remove();
});
listItem.appendChild(taskSpan);
listItem.appendChild(deleteBtn);
document.getElementById('taskList').appendChild(listItem);
input.value = '';
}
// Allow adding tasks by pressing Enter
document.getElementById('taskInput').addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
addTask();
}
});
</script>
</body>
</html>
Users can add new tasks by typing and clicking "Add Task" or pressing Enter. Each task has a "Delete" button to remove it from the list
My Task List [Enter a new task ] [Add Task] ? Learn HTML basics [Delete] ? Practice CSS styling [Delete] ? Study JavaScript [Delete]
Using Event Delegation
For dynamically added elements, event delegation is a powerful technique that attaches event listeners to parent elements instead of individual child elements.
Example Event Delegation Approach
<!DOCTYPE html>
<html>
<head>
<title>Event Delegation Example</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
<h2>Dynamic Button List</h2>
<button onclick="addButton()">Add New Button</button>
<div id="button-container" style="margin-top: 15px;"></div>
<script>
let buttonCount = 1;
// Event delegation - single listener on container
document.getElementById('button-container').addEventListener('click', function(e) {
if (e.target.tagName === 'BUTTON' && e.target.classList.contains('dynamic-btn')) {
e.target.remove();
}
});
function addButton() {
const newButton = document.createElement('button');
newButton.textContent = `Button ${buttonCount} (Click to Remove)`;
newButton.className = 'dynamic-btn';
newButton.style.margin = '5px';
newButton.style.padding = '8px 12px';
newButton.style.backgroundColor = '#007bff';
newButton.style.color = 'white';
newButton.style.border = 'none';
newButton.style.borderRadius = '4px';
newButton.style.cursor = 'pointer';
document.getElementById('button-container').appendChild(newButton);
buttonCount++;
}
</script>
</body>
</html>
This approach uses a single event listener on the container that handles clicks for all dynamically added buttons, improving performance and simplifying code maintenance.
Conclusion
Adding and removing values on click events in HTML is accomplished through JavaScript's addEventListener() and remove() methods. The addEventListener() method attaches click handlers to elements, while remove() deletes elements from the DOM. For dynamic content, event delegation provides an efficient way to handle events on elements that are added after the initial page load.
