Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

remove items from DOM and array

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #myList {
            list-style: none;
        }
        li {
            padding: 10px;
            max-width: 300px;
            background-color: rgb(186, 255, 129);
            font-size: larger;
            font-weight: bold;
            border-style: double;
            border-radius: 10px;
            text-align: center;
            margin: 5px;
        }
        .remove-btn {
            float: right;
            background-color: red;
            color:black;
            
        }
        #itemAdd {
            padding: 10px;
            font-size: larger;
            text-align: center;
        }
        #itemName {
            padding: 10px;
            max-width: 300px;
            font-size: larger;
            font-weight: bold;
            border-style: double;
            text-align: center;
        }
    </style>
</head>
<body>
    <div class="container main">
        <form action="" method="post">
        <input type="text" id="itemName">
        <button onclick="addItem()" id="itemAdd">ADD</button>
        </form>
        <div>
            <ul id="myList">
                
            </ul>
        </div>
    </div>
    <script>

        let items = [];

        const addItem = () => {
            event.preventDefault();
            let myList = document.getElementById('myList');
            let listItem = document.createElement('li');
            listItem.innerText = itemName.value + "  ";
            myList.append(listItem);
            let removeButton = document.createElement('button');
            removeButton.innerText = "-";
            removeButton.className = "remove-btn"
            removeButton.addEventListener('click', removeItem);
            listItem.append(removeButton);
            items.push(itemName.value);
            document.forms[0].reset();
        }

        const removeItem = () => {
            let item = event.currentTarget.parentNode;
            item.remove();
            let itemIndex = items.indexOf(item);
            items.splice(itemIndex, 1);
        }
    </script>
</body>
</html>
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #remove #items #DOM #array
ADD COMMENT
Topic
Name
6+6 =