How to Remove an HTML Element Using JavaScript

How to remove an HTML element using Javascript?

What's happening is that the form is getting submitted, and so the page is being refreshed (with its original content). You're handling the click event on a submit button.

If you want to remove the element and not submit the form, handle the submit event on the form instead, and return false from your handler:

HTML:

<form  onsubmit="return removeDummy(); ">
<input type="submit" value="Remove DUMMY"/>
</form>

JavaScript:

function removeDummy() {
var elem = document.getElementById('dummy');
elem.parentNode.removeChild(elem);
return false;
}

But you don't need (or want) a form for that at all, not if its sole purpose is to remove the dummy div. Instead:

HTML:

<input type="button" value="Remove DUMMY" onclick="removeDummy()" />

JavaScript:

function removeDummy() {
var elem = document.getElementById('dummy');
elem.parentNode.removeChild(elem);
return false;
}

However, that style of setting up event handlers is old-fashioned. You seem to have good instincts in that your JavaScript code is in its own file and such. The next step is to take it further and avoid using onXYZ attributes for hooking up event handlers. Instead, in your JavaScript, you can hook them up with the newer (circa year 2000) way instead:

HTML:

<input id='btnRemoveDummy' type="button" value="Remove DUMMY"/>

JavaScript:

function removeDummy() {
var elem = document.getElementById('dummy');
elem.parentNode.removeChild(elem);
return false;
}
function pageInit() {
// Hook up the "remove dummy" button
var btn = document.getElementById('btnRemoveDummy');
if (btn.addEventListener) {
// DOM2 standard
btn.addEventListener('click', removeDummy, false);
}
else if (btn.attachEvent) {
// IE (IE9 finally supports the above, though)
btn.attachEvent('onclick', removeDummy);
}
else {
// Really old or non-standard browser, try DOM0
btn.onclick = removeDummy;
}
}

...then call pageInit(); from a script tag at the very end of your page body (just before the closing </body> tag), or from within the window load event, though that happens very late in the page load cycle and so usually isn't good for hooking up event handlers (it happens after all images have finally loaded, for instance).

Note that I've had to put in some handling to deal with browser differences. You'll probably want a function for hooking up events so you don't have to repeat that logic every time. Or consider using a library like jQuery, Prototype, YUI, Closure, or any of several others to smooth over those browser differences for you. It's very important to understand the underlying stuff going on, both in terms of JavaScript fundamentals and DOM fundamentals, but libraries deal with a lot of inconsistencies, and also provide a lot of handy utilities — like a means of hooking up event handlers that deals with browser differences. Most of them also provide a way to set up a function (like pageInit) to run as soon as the DOM is ready to be manipulated, long before window load fires.

How can I remove/delete a HTML element using JavaScript?

You're confusing the string identifier 'warning' with a warning variable:

let warning = document.createElement('p');

This is setting the variable warning to a paragraph element.

if (document.getElementById(warning) == null){

Here you're passing that warning variable, which is set to an HTML element to getElementById, so it's never going to find it.

const error = getElementById(warning)
error.remove()

Here you're making that same mistake.

With some adjustments it'll work a bit better:

function createWarning(message){
const existingWarning = document.getElementById('warning');
if (existingWarning) {
existingWarning.remove();
}

const warning = document.createElement('p');
warning.innerHTML = message;
warning.classList.add('warning');
warning.setAttribute('id','warning');
input.insertAdjacentElement('afterend',warning);
}

Is it possible to remove an html element and keep your children with javascript?

It's possible with vanilla JavaScript by deep cloning the node of grandson before removing anything else. and then appending it back to the parent. Of course if you want to place it somewhere else, you need to append needed logic of DOM traversing. (CSS section is only for visual validation of the result)

const grandson = document.querySelector('.grandson');const father = grandson.closest('.father');const clonedGrandson = grandson.cloneNode(true);
father.querySelector('.son').remove();father.appendChild(clonedGrandson);
.father {  background-color: red;  padding: 20px; }  .son {  background-color: blue;  padding: 20px; }  .grandson {  background-color: green;  padding: 20px; }
<div class="father">  <fieldset class="son">    <div class="grandson">      <p>Save me</p>    </div>  </fieldset></div>

Remove HTML Elements with values using javascript

Remove the <select> elements with .remove().

document.querySelectorAll("select").forEach(el => el.remove());
<span>Span First</span>
<select>
<option>opt 01</option>
<option>opt 02</option>
</select>
<span>Span Second</span>
<select>
<option>opt 11</option>
<option>opt 12</option>
</select>

programmatically removing html element

It's a class so it's not with a hash. It should be then like this:

$(".forDelete").remove();

Otherwise if you want to use the idi of your element:

$("#world-map").remove();

Also remember JS is caps sensitive so it is not .Remove but .remove()

Remove self element onclick

You have to pass this through the function call in html onclick so it could refer to the element then you have to use it as parameter in the function definition, otherwise, if you use this in the function definition, it will just refer to the window object.

This will work fine

function remove(el) {  var element = el;  element.remove();}
<div id="i" onclick="remove(this)">Sample text</div>

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.

Is there a way to completely remove an HTML element using Javascript?

Yes

JavaScript

var parent = document.getElementById('parentElementID');
var child = document.getElementById('childElementID');
parent.removeChild(child);

jQuery

$('#parentElementID').remove('#childElementID');


Related Topics



Leave a reply



Submit