I know that augmenting native DOM functions isn't always the best or most popular solution, but this works fine for modern browsers.

Element.prototype.remove = function() {
    this.parentElement.removeChild(this);
}
NodeList.prototype.remove = HTMLCollection.prototype.remove = function() {
    for(var i = this.length - 1; i >= 0; i--) {
        if(this[i] && this[i].parentElement) {
            this[i].parentElement.removeChild(this[i]);
        }
    }
}

And then you can remove elements like this

document.getElementById("my-element").remove();

or

document.getElementsByClassName("my-elements").remove();

Note: this solution doesn't work for IE 7 and below. For more info about extending the DOM read this article.

EDIT: Reviewing my answer in 2019, node.remove() has come to the rescue and can be used as follows (without the polyfill above):

document.getElementById("my-element").remove();

or

[...document.getElementsByClassName("my-elements")].map(n => n && n.remove());

These functions are available in all modern browsers (not IE). Read more on MDN.

Answer from Johan Dettmar on Stack Overflow
๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ API โ€บ Element โ€บ remove
Element: remove() method - Web APIs | MDN
html ยท <div id="div-01">Here is div-01</div> <div id="div-02">Here is div-02</div> <div id="div-03">Here is div-03</div> js ยท const element = document.getElementById("div-02"); element.remove(); // Removes the div with the 'div-02' id ยท The remove() method is not scoped into the with statement.
๐ŸŒ
W3Schools
w3schools.com โ€บ jsref โ€บ met_element_remove.asp
HTML DOM Element remove Method
Bitwise AND Bitwise OR Bitwise NOT Bitwise XOR Bitwise Left Bitwise Right Bitwise Signed JS Misc Operators ยท : ?. ... () ? x : y => delete in instanceof typeof void JS Precedence JS Promises
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ javascript โ€บ how-to-remove-an-html-element-using-javascript
How to remove an HTML element using JavaScript ? - GeeksforGeeks
July 12, 2025 - The remove() method directly removes an HTML element from the DOM. To use it, simply select the element you want to remove and call element.remove(). This approach is straightforward, requires no parent reference, and instantly deletes the element ...
๐ŸŒ
Devcamp
utahedu.devcamp.com โ€บ cts-2018 โ€บ guide โ€บ guide-removing-html-elements-javascript
Guide to Removing HTML Elements with JavaScript
Now those elements are completely removed from the DOM and you do not have to worry about them whatsoever and so this is actually a good way of being able to remove any items that you no longer want inside of that document object model. <!DOCTYPE html> <html lang='en'> <head> <meta charset='UTF-8'> <title></title> </head> <body> <div class="widget"> <input type="text" id="chat-input"> <button id="msgBtn" onclick="sendMessage()">Submit</button> <button onclick="clearMessages()">Clear Messages</button> <div class="chat-wrapper"></div> </div> </body> <script> function sendMessage() { const newDiv
๐ŸŒ
jQuery
api.jquery.com โ€บ remove
.remove() | jQuery API Documentation
Similar to .empty(), the .remove() method takes elements out of the DOM. Use .remove() when you want to remove the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed.
๐ŸŒ
Medium
medium.com โ€บ @tom.hendrych โ€บ creating-and-removing-html-elements-with-javascript-372bbd4cfdcc
Creating and removing HTML elements with JavaScript | by Tom Hendrych | Medium
January 26, 2024 - To do so, we will find the element with method querySelector() . Then we check if we found our desired element. If not, then we will print the message into the console and stop the execution of the rest of the code in our function.
Top answer
1 of 11
207

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.

2 of 11
40

Just do this element.remove();

Try it here LOOK

http://jsfiddle.net/4WGRP/

Find elsewhere
๐ŸŒ
Mimo
mimo.org โ€บ glossary โ€บ javascript โ€บ removing-an-element
Learn how to Remove and Element in JavaScript
Remove the last element of an array in JavaScript using .pop() ... Become a full-stack developer. Learn HTML, CSS, JavaScript, and React as well as NodeJS, Express, and SQL
๐ŸŒ
JavaScript Tutorial
javascripttutorial.net โ€บ home โ€บ remove a dom element
How to Remove a DOM Element in JavaScript
August 18, 2022 - To remove an element from the DOM, you can also use the remove() method of the element. All major browsers support the remove() method except for IE. Since IE was deprecated, you can use the remove() method today.
๐ŸŒ
Catalin
catalin.red โ€บ removing-an-element-with-plain-javascript-remove-method
Removing an element with the plain JavaScript remove() method - Catalin Red
Remove an element with the plain JavaScript remove() method available in the current DOM4 specs along with other mutation methods like append(), prepend(), before(), after() and replace().
๐ŸŒ
Quora
quora.com โ€บ How-do-I-remove-an-element-from-the-DOM-using-Javascript
How to remove an element from the DOM using Javascript - Quora
Any criticism you may have, is like to shouting into the void of Pre-ES6 Javascript. Even after 30 years of many, many people trying to fix the still flawed JS, it is still mediocre at best. I know we are stuck with it for client side logic, but it doesnโ€™t really belong anywhere else, ie. server-side logic. โ€”โ€”โ€” ยท Itโ€™s easiest if you are using JQuery, since selection is more straightforward, and it also has a remove() function built in.
๐ŸŒ
Go Make Things
gomakethings.com โ€บ removing-an-element-from-the-dom-with-vanilla-js
Removing an element from the DOM with vanilla JS | Go Make Things
If you just want to hide the element ... = 'none'; If you want to remove the element from the DOM entirely, you can use the removeChild() method....
Top answer
1 of 2
1

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);
}
2 of 2
0

Call getElementById from document and use the string-based ID for 'warning' instead of the reference to the element as your argument to document.getElementById() Corrected code is below:

const input = document.querySelector('#emailInput');
const form = document.querySelector('#myForm')
const button = document.querySelector('#notify')
const validRegex = /^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;

form.addEventListener('submit', function (e){
    e.preventDefault()
});

button.addEventListener('click', validateEmail)

function validateEmail(){
    let inputValue = input.value;
    if(inputValue.match(validRegex)){
        createWarning('Email sent!')
    }
    else if(inputValue == ''){
        createWarning('Please provide an email!');
    }
    else{
        createWarning('Please provid a valid email address')
    }
}

function createWarning(message){
    let warning = document.createElement('p');
    let warningId = 'warning';
    if (document.getElementById(warningId) == null) {
        warning.innerHTML = message;
        warning.classList.add('warning');
        warning.setAttribute('id', warningId);
        input.insertAdjacentElement('afterend',warning);
    }    
    else {
        const error = document.getElementById(warningId)
        error.remove()
    }    
}
@import url('https://fonts.googleapis.com/css2?family=Libre+Franklin:wght@300;600;700&display=swap');

*{
     margin: 0;
     padding: 0;
     box-sizing: border-box;
}

body{
    background-color: whitesmoke;
    font-size: 20px;
    font-family: 'Libre Franklin', sans-serif;
    display: flex;
    flex-direction: column;
    align-content: space-between;
    height: 100vh;
}

.container{
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-evenly;
    height: 100%;
}

.title{
    display: flex;
    align-items: center;
    justify-content: center;
}

.company-name{
    font-family: 'Libre Franklin', sans-serif;
    font-weight: 700;
    font-size: 20px;
}

.dot{
    color: hsl(223, 87%, 63%);
}

.intro{
    display: flex;
    flex-direction: column;
    align-items: center;
    align-content: space-between;
    gap: 15px;
    justify-content: space-between;
}

.subtitle h2{
    font-weight: 600;
    font-size: 20px;
}

.launching{
    color: rgba(190, 160, 83, 0.602);
    font-weight: 200;
}

.paragraph p{
    font-weight: 300;
    font-size: 14px;
    color: rgb(41, 37, 0);
}

form{
    display: flex;
    align-items: center;
    align-content: space-between;
    flex-direction: column;
}

#emailInput{
    border-radius: 50px;
    border: 1px solid hsl(223, 100%, 88%);
    width: 100%;
    padding: 10px 35px;
    font-family: 'Libre Franklin', sans-serif;
}

.warning{
    color: hsl(354, 100%, 66%);
    font-size: small;
    font-family: 'Libre Franklin', sans-serif;
    margin: 5px;
}

#emailInput:focus{
    outline: none;
}

#notify{
    background-color: hsl(223, 87%, 63%);
    color: whitesmoke;
    border-radius: 50px;
    padding: 10px 20px;
    width: 100%;
    border: 1px solid rgba(88, 78, 78, 0);
    font-weight: bold;
    margin-top: 15px;
}

.social-media{
    width: 200px;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    align-content: space-between;
    justify-items: center;
}

.around{
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
    border: 1px solid hsla(0, 0%, 59%, 0.192);
    border-radius: 50%;
    width: 30px;
    height: 30px;
}
.fab{
    color: hsl(223, 87%, 63%);
    font-size: medium;
}

.attribution { font-size: 11px; text-align: center; }
.attribution a { color: hsl(228, 45%, 44%); }
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- displays site properly based on user's device -->

  <link rel="icon" type="image/png" sizes="32x32" href="./images/favicon-32x32.png">
  <link rel="stylesheet" href="style.css">
  <script src="https://kit.fontawesome.com/b5c693247f.js" crossorigin="anonymous"></script>
  <title>Frontend Mentor | Ping coming soon page</title>
</head>
<body>
  <div class="container">
    <div class="title">
      <h1 class="company-name">PING<span class="dot">.</span></h1>
    </div>
    <div class="intro">
      <div class="subtitle"><h2><span class="launching">We are launching</span> soon!</h2></div>
      <div class="paragraph"><p>Subscribe and get notified</p></div>
      <div class="form-container">
        <form id="myForm" name="myForm">
          <input type="email" id="emailInput" name="emailInput" placeholder="Your email address...">
          <button type="submit" id="notify">Notify Me</button>
        </form>
      </div>
    </div>
    <div class="img-container">
      <img src="images/illustration-dashboard.png" alt="Dashboard Image" width="300" height="250">
    </div>
    <div class="social-media">
      <div class="around"><i class="fab fa-facebook-f"></i></div>
      <div class="around"><i class="fab fa-twitter"></i></div>
      <div class="around"><i class="fab fa-instagram"></i></div>
    </div>
  </div>

  <footer>
    <p class="attribution">
      Challenge by <a href="https://www.frontendmentor.io?ref=challenge" target="_blank">Frontend Mentor</a>. 
      Coded by <a href="https://github.com/HBortolim">Henrique Bortolim</a>.
    </p>
  </footer>
  <script src="app.js"></script>
</body>
</html>

๐ŸŒ
SoftAuthor
softauthor.com โ€บ home โ€บ javascript โ€บ remove html element from dom in javascript
Remove HTML Element From DOM in JavaScript โ€ข SoftAuthor
August 10, 2022 - Assign it to the constant boxes. Get the orange box by its index value, which is 2 in this case. Finally, call the remove() method on the div element object which will remove itself from the DOM hierarchy.
๐ŸŒ
Wikibooks
en.wikibooks.org โ€บ wiki โ€บ JavaScript โ€บ Removing_elements
JavaScript/Removing elements - Wikibooks, open books for an open world
July 20, 2008 - // get element const anchor = document.getElementById("anchor"); // remove attribute anchor.removeAttribute("href"); The element itself, including the text of the link, keeps alive, but you cannot navigate anymore.
๐ŸŒ
Bobby Hadz
bobbyhadz.com โ€บ blog โ€บ javascript-remove-dom-element-by-id
Remove a DOM element by ID using JavaScript | bobbyhadz
If you need to remove the element without removing its children, use this approach instead. ... Copied!<!DOCTYPE html> <html lang="en"> <head> <title>bobbyhadz.com</title> <meta charset="UTF-8" /> </head> <body> <!-- ๐Ÿ‘‡๏ธ Only remove this div (not children) --> <div id="parent"> <span>Child 1</span> <span>Child 2</span> </div> <script src="index.js"></script> </body> </html>
๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ API โ€บ HTMLSelectElement โ€บ remove
HTMLSelectElement: remove() method - Web APIs | MDN
The HTMLSelectElement.remove() method removes the element at the specified index from the options collection for this select element.