How to add and remove names on button click with JavaScript?

JavaScript allows you to dynamically add and remove names from a list using DOM manipulation methods. This functionality is commonly used in todo lists, user management interfaces, and interactive forms.

HTML Structure

First, we need a basic HTML structure with an input field, buttons, and a container for the names list:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add and Remove Names</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            padding: 20px;
        }
        .red {
            border: 2px solid red;
        }
        .name-item {
            margin: 5px 0;
            padding: 10px;
            background-color: #f0f0f0;
            border-radius: 5px;
        }
        button {
            margin-left: 10px;
            padding: 5px 10px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <h1>Add A New Name</h1>
    <div>
        <input type="text" id="nameInput" placeholder="Enter a name...">
        <button id="addNameButton">Add Name</button>
    </div>
    <ul id="namesList"></ul>
</body>
</html>

Complete JavaScript Implementation

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add and Remove Names</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            padding: 20px;
            max-width: 600px;
            margin: 0 auto;
        }
        .red {
            border: 2px solid red;
        }
        .name-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin: 10px 0;
            padding: 10px;
            background-color: #f0f0f0;
            border-radius: 5px;
        }
        button {
            padding: 8px 15px;
            cursor: pointer;
            border: none;
            border-radius: 3px;
        }
        #addNameButton {
            background-color: #4CAF50;
            color: white;
            margin-left: 10px;
        }
        .remove-btn {
            background-color: #f44336;
            color: white;
        }
        input {
            padding: 8px;
            border: 2px solid #ddd;
            border-radius: 3px;
        }
    </style>
</head>
<body>
    <h1>Add and Remove Names</h1>
    <div>
        <input type="text" id="nameInput" placeholder="Enter a name...">
        <button id="addNameButton">Add Name</button>
    </div>
    <ul id="namesList"></ul>

    <script>
        const nameInput = document.getElementById('nameInput');
        const addButton = document.getElementById('addNameButton');
        const namesList = document.getElementById('namesList');

        // Add name function
        function addName() {
            const name = nameInput.value.trim();
            
            if (name.length === 0) {
                nameInput.classList.add('red');
                return;
            }
            
            // Remove red border if name is valid
            nameInput.classList.remove('red');
            
            // Create list item
            const listItem = document.createElement('li');
            listItem.className = 'name-item';
            
            // Create name display
            const nameDiv = document.createElement('div');
            nameDiv.textContent = name;
            
            // Create remove button
            const removeButton = document.createElement('button');
            removeButton.textContent = 'Remove';
            removeButton.className = 'remove-btn';
            removeButton.onclick = function() {
                removeName(this);
            };
            
            // Append elements
            listItem.appendChild(nameDiv);
            listItem.appendChild(removeButton);
            namesList.appendChild(listItem);
            
            // Clear input
            nameInput.value = '';
        }

        // Remove name function
        function removeName(button) {
            button.parentElement.remove();
        }

        // Event listeners
        addButton.addEventListener('click', addName);
        
        // Allow Enter key to add name
        nameInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                addName();
            }
        });
        
        // Remove red border when user starts typing
        nameInput.addEventListener('input', function() {
            this.classList.remove('red');
        });
    </script>
</body>
</html>

How It Works

The implementation uses several key JavaScript methods:

  • DOM Selection: getElementById() to get references to HTML elements
  • Element Creation: createElement() to create new list items and buttons
  • Event Handling: addEventListener() for button clicks and key presses
  • Element Removal: remove() method to delete elements from the DOM

Key Features

This implementation includes several user-friendly features:

  • Input Validation: Prevents adding empty names and shows visual feedback
  • Enter Key Support: Users can press Enter to add names
  • Visual Feedback: Red border appears for invalid input
  • Clean Interface: Proper styling and layout for better user experience

Alternative Approach Using innerHTML

You can also use innerHTML for a more concise approach:

<script>
    const nameInput = document.getElementById('nameInput');
    const addButton = document.getElementById('addNameButton');
    const namesList = document.getElementById('namesList');

    function addName() {
        const name = nameInput.value.trim();
        
        if (name.length === 0) {
            nameInput.classList.add('red');
            return;
        }
        
        nameInput.classList.remove('red');
        
        const listItem = `
            <li class="name-item">
                <div>${name}</div>
                <button class="remove-btn" onclick="removeName(this)">Remove</button>
            </li>
        `;
        
        namesList.innerHTML += listItem;
        nameInput.value = '';
    }

    function removeName(button) {
        button.parentElement.remove();
    }

    addButton.addEventListener('click', addName);
</script>

Comparison of Methods

Method Performance Security Flexibility
createElement() Better Safer More control
innerHTML Good Risk with user input Simpler syntax

Conclusion

Adding and removing names dynamically demonstrates core JavaScript DOM manipulation concepts. Use createElement() for better performance and security, especially when handling user input. Always validate input and provide clear visual feedback to users.

Updated on: 2026-03-15T23:18:59+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements