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

delete button javascript – JavaScript Code is given below, In this full source code we have used remove() method which removes or deletes the html element from the DOM. Removing an element is much easier, as it only requires the element’s ID.

delete button javascript

How to add and remove names on button click with JavaScript? – To create, use add() method, whereas to delete created and appended element, you can use remove().

using The remove() Method

function removeElement(elementId) {
	// Removes an element from the document.
	 var element = document. getElementById(elementId);
	 element. parentNode. removeChild(element);
}

The remove() method removes the element from the DOM.

Also Read This πŸ‘‰   php ajax post - jQuery AJAX Post Example with PHP and JSON

HTML Code

index.html

<!DOCTYPE html>
<html>
<body>

Name: <input type="text" id="myText" value="">
<br/>
<br/>
Age: <input type="number" name="age">

<button onclick="getProducts()">Try it</button>

<script>

function getProducts() {
  
    var input = document.getElementsByTagName('input')[0].value;
    var agenum = document.getElementsByTagName('input')[1].value;
    var div = document.createElement('div');
    div.style.border = '2px solid red';
    div.style.padding = '10px';
    div.style.display = 'block';
    document.body.appendChild(div);
  
    var result = 'Name: ' + input + '<br/>' + 'Age: ' + agenum;
    div.innerHTML = result;
    
    //create your delete button after you click try it
    var del = document.createElement('button');
    del.style.textDecoration = 'none';
    del.innerHTML = 'Remove this person?';
    del.style.color = 'white';
    del.style.backgroundColor = 'blue';
    //assign a function for it when clicked
    del.onclick = function() { deleteButton(div,this)}; 
    document.body.appendChild(del);
   <!--  deleteButton(div);  --> 
}

function deleteButton(x,y) {
	  
    var parent = document.getElementsByTagName("BODY")[0];
    //remove the div
    parent.removeChild(x);
    //remore the button
    parent.removeChild(y);
    
}


</script>

</body>
</html>

Delete HTML Element using JavaScript

HTML Code is given below.

<!DOCTYPE html>
<html>
<head>
    <title>Remove HTML Element using JavaScript</title>
</head>
<body>

    <h1 id='heading'>HowToCodeSchool.com</h1>
    <button onclick='remove()'>Remove Heading</button>
    
</body>
</html>

Free Live Chat for Any Issue

JavaScript Code

<script>
function remove()
{
var element = document.getElementById("heading");
element.remove();
}
</script>

Don’t Miss : How To Add Edit And Delete Button In Datatable Using Php?

I hope you get an idea about delete button javascript.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.