JavaScript Dom Remove Element

JavaScript DOM remove element

removeChild should be invoked on the parent, i.e.:

parent.removeChild(child);

In your example, you should be doing something like:

if (frameid) {
frameid.parentNode.removeChild(frameid);
}

Remove element by id

Update 2011

This was added to the DOM spec back in 2011, so you can just use:

element.remove()

The DOM is organized in a tree of nodes, where each node has a value, along with a list of references to its child nodes. So element.parentNode.removeChild(element) mimics exactly what is happening internally: First you go the parent node, then remove the reference to the child node.

As of DOM4, a helper function is provided to do the same thing: element.remove(). This works in 96% of browsers (as of 2020), but not IE 11.

If you need to support older browsers, you can:

  • Remove elements via the parent node
  • Modify the native DOM functions, as in Johan Dettmar's answer, or
  • Use a DOM4 polyfill.

Best way to remove an Element from the DOM if it exists

With the HTML structure that you have, the simplest way to know if there is a span element just after the current input element that is being validated is to just check the nextElementSibling of the input element to see if it is a span. If it is, then you need to remove the nextElementSibling and if not, you can add it.

For example, in your first validation:

var fName = document.getElementById('fName');
// .getElementById() is faster than .querySelector() when looking for id's
var nameContainer = document.getElementById('nameContainer');

// Is the next element sibling of the field a span?
if(nameContainer.nextElementSibling.nodeName === "SPAN"){
// span already exists - remove it
nameContainer.parentNode.removeChild(nameContainer.nextElementSibling);
} else {
// span does not exist - create and add it
var infoSpan = document.createElement('span');
nameContainer.appendChild(infoSpan);
}

Having said that, this is entirely unnecessary and hinders performance because you are modifying the DOM over and over.

Since you need a span no matter what, just create them statically in the HTML and then just update their textContent (don't use .innerHTML unless you have HTML to be parsed).

var regName = /^[A-Za-z]+$/;var regEmail = /^[A-Za-z]+$/;var regUserName = /^[A-Za-z]+$/;var regPassword = /^[A-Za-z]+$/;
var validate = { validateName: function() { var fName = document.getElementById('fName'); var nameContainer = document.querySelector('#nameContainer'); var infoSpan = document.getElementById('nameInfo'); fName.classList.remove('errorBorder');
if (fName.value.match(regName)) { console.log('Name Valid'); infoSpan.classList.add('checkmark'); infoSpan.textContent = '*checkmark*'; } else if(fName.value === '') { console.log('input is empty'); } else { console.log('Name Invalid'); fName.classList.add('errorBorder'); infoSpan.classList.add('error'); infoSpan.textContent = '*invalid input'; } }, validateEmail: function() { var fEmail = document.getElementById('fEmail'); var emailContainer = document.querySelector('#emailContainer'); var infoSpan = document.getElementById('emailInfo'); fEmail.classList.remove('errorBorder'); if (fEmail.value.match(regEmail)) { console.log('Email Valid'); infoSpan.classList.add('checkmark'); infoSpan.textContent = '*checkmark*'; } else { console.log('Email Invalid'); fEmail.classList.add('errorBorder'); infoSpan.classList.add('error'); infoSpan.textContent = '*invalid input';
} }, validateUserName: function() { var fUserName = document.getElementById('fUserName'); var userNameContainer = document.querySelector('#userNameContainer'); var infoSpan = document.getElementById('userNameInfo'); fUserName.classList.remove('errorBorder');
if (fUserName.value.match(regUserName)) { console.log('User Name Valid'); infoSpan.classList.add('checkmark'); infoSpan.textContent = '*checkmark*'; } else { console.log('User Name Invalid'); fUserName.classList.add('errorBorder'); infoSpan.classList.add('error'); infoSpan.textContent = '*invalid input'; } }, validatePassword: function() { var fPassword = document.getElementById('fPassword'); var passwordContainer = document.querySelector('#passwordContainer'); var infoSpan = document.getElementById('passwordInfo'); fPassword.classList.remove('errorBorder');
if (fPassword.value.match(regPassword)) { console.log('Passowrd Valid'); infoSpan.classList.add('checkmark'); infoSpan.textContent = '*checkmark*'; } else { console.log('Passowrd Invalid'); fPassword.classList.add('errorBorder'); infoSpan.classList.add('error'); infoSpan.textContent = '*invalid input'; } }};
function onSubmit() { validate.validateName(); validate.validateEmail(); validate.validateUserName(); validate.validatePassword();}
/* Styles go here */
label, span { font-family: sans-serif;}
label { font-size: 14px;}
form div { margin: 10px 0;}
label { display: inline-block; width: 85px;}
.errorBorder { border: thin red solid;}
span.error { color: red; font-size: 12px; display: inline-block; margin-left: 10px;}
span.checkmark { color: green; font-weight: bold;}
<form onsubmit="return false">            <div id="nameContainer">        <label>Full Name: </label>        <input type="text" id="fName"><span id="nameInfo"></span>      </div>            <div id="emailContainer">        <label>Email: </label>        <input type="text" id="fEmail"><span id="emailInfo"></span>      </div>            <div id="userNameContainer">        <label>User Name: </label>        <input type="text" id="fUserName"><span id="userNameInfo"></span>      </div>            <div id="passwordContainer">        <label>Password: </label>        <input type="password" id="fPassword"><span id="passwordInfo"></span>      </div>            <br />            <input type="submit" value="submit" onclick="onSubmit()">          </form>

Remove all child elements of a DOM node in JavaScript

In 2022+, use the replaceChildren() API!

Replacing all children can now be done with the (cross-browser supported) replaceChildren API:

container.replaceChildren(...arrayOfNewChildren);

This will do both:

  • remove all existing children, and
  • append all of the given new children, in one operation.

You can also use this same API to just remove existing children, without replacing them:

container.replaceChildren();

This is fully supported in Chrome/Edge 86+, Firefox 78+, and Safari 14+. It is fully specified behavior. This is likely to be faster than any other proposed method here, since the removal of old children and addition of new children is done without requiring innerHTML, and in one step instead of multiple.

removing DOM element by clicking on it

Since your button is added dynamically you can't bind an event directly to it because it doesn't exist yet. Try this example from the jQuery documentation to bind to the body instead of your button.

$( "body" ).on( "click", "ID of your button", function() {
console.log( $( this ).text() );
});

How to delete a DOM element from an array after you've clicked on it?

With the use of JavaScript DOM API such as Node.removeChild(), Element.remove() and Node.parentNode, your task can be solved with this code:

const input = document.getElementById('play');
const todo = document.getElementById('todo');
const done = document.getElementById('done');

function handleSubmit(event) {
event.preventDefault();

// create new "todo" item
const newTodo = document.createElement('li');
newTodo.textContent = input.value;
todo.append(newTodo);

// clean the input field
input.value = '';

// listen to "click" event on the created item to move it to "done" section
newTodo.addEventListener('click', moveToDone);
}

function moveToDone(event) {
// remove "click"-listener to prevent event listener leaks
event.target.removeEventListener('click', moveToDone);

// move clicked todo-element to "done" section
const newDone = event.target.parentNode.removeChild(event.target);
done.append(newDone);

// listen to "click" event on the moved item to then completely delete it
newDone.addEventListener('click', removeFromDone);

debugElementsLeak();
}

function removeFromDone(event) {
// remove "click"-listener to prevent event listener leaks
event.target.removeEventListener('click', removeFromDone);

// complete remove clicked element from the DOM
event.target.remove();

debugElementsLeak();
}

function debugElementsLeak() {
const todoCount = todo.childElementCount;
const doneCount = done.childElementCount;
console.log({ todoCount, doneCount });
}
<div id="flex">
<form class="form" onsubmit="handleSubmit(event)">
<input placeholder="New item" type="text" id="play">
<button>Add item</button>
</form>

<div id="left">
<h1>To-do:</h1>
<p class="instruction"><em>(Click over to mark as done)</em></p>
<ol id="todo"></ol>
</div>

<div id="right">
<h1>Done:</h1>
<p class="instruction"><em>(Click over to delete it)</em></p>
<p id="placeholder"></p>
<ol id="done"></ol>
</div>
</div>

Delete a dom element using a button within it, vanilla JS

Because you want to add the same logic on multiple buttons you should use classes instead of ids. An ID should be unique. With Element.closest() you can find the closest parent from where the click happened until it finds a node that matches the provided selector string. Read the comments inside the code sample here

const deleteButtons = document.querySelectorAll('.del'); // will give you an array of buttons

deleteButtons.forEach( button => {
button.addEventListener('click', removeMe); // add the event listener to each button
});

function removeMe() {
this.closest('li').remove(); // this is the button, from there you want to move up in DOM and find the closes <li> to remove
}
<h1>The List</h1>
<ul>
<li>Delete me<button class="del">x</button></li>
<li>Delete me too<button class="del">x</button></li>
</ul>

DOM manupulation: how to remove an element from list of json data dymically in javascript DOM

You can surely remove the data from DOM when you delete it from the list. I would suggest a simple approach where you have to assign an id to all the main div that you create dynamically. And later when the deleteEle function is called you remove that from DOM.

Add following line to createEle function of yours

const createEle = (data, idx) => {
*** rest code***
let remove = document.createElement('div');
let update = document.createElement('div');
main.id =idx; //NEW LINE ADDED
main.className = "main";
*** rest code***
}

Update your deleteEle as follows

const deleteEle = (idx) => {
names.nameList.splice(idx - 1, 1)
console.log("deleted", idx, names.nameList);
document.getElementById(idx).remove();
}

Using remove() to ensure element is not visible in DOM or by viewing source code

The browser receives the HTML document, converts it into a DOM, and runs the JS which modifies the DOM.

The source code is unchanged. It's the source code, not a reflection of the current state.

You wouldn't want web browsers to be able to rewrite the code on your server: That would lead to your homepage being vandalised with new spam 30 times a second.

If you want to change the HTML that the server sends to the browser (or sends to the search engine indexing bot) then you need to fix it on the server.



Related Topics



Leave a reply



Submit