145

I am a total newbie. Can somebody tell me how to remove an HTML element using the original Javascript not jQuery.

index.html

<html>
<head>
 <script type="text/javascript" src="myscripts.js" > </script>
 <style>
 #dummy {
  min-width: 200px;
  min-height: 200px;
  max-width: 200px;
  max-height: 200px;
  background-color: #fff000;
 }
 </style>
</head>
<body>
 <div id="dummy"></div>

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

myscripts.js

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

What happens when I click the submit button, is that it will disappear for a very very short time and then appear back immediately. I want to completely remove the element when I click the button.

Flip
  • 6,233
  • 7
  • 46
  • 75
Newbie Coder
  • 10,684
  • 19
  • 41
  • 53
  • What if I click it, spot an error and press *stop* ? – alex May 09 '11 at 06:09
  • Sorry, it's of topic but it is actually really funny, that he/she named him-/herself "Newbie Coder" and now the profile has a reputation of around 9000. Asking something in the "good old times" is really profitable nowadays. :) – Rene Jun 13 '20 at 13:42

11 Answers11

209

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Change it to `type="button"` or put `return false;` in your JS function – Pav May 09 '11 at 06:13
  • @Pav: I think I'll stick to submit because this is just an experimental exercise. I will be doing some projects that uses submit so I better get used to it... Thanks anyway for the idea. – Newbie Coder May 09 '11 at 06:18
  • @Newbie: I added a few further notes. – T.J. Crowder May 09 '11 at 06:21
  • 2
    why not just do elem.remove(); – Muhammad Umer Jul 10 '13 at 00:01
  • what does return false do –  Sep 13 '13 at 09:29
  • @bhawin: Actually, I probably shouldn't have `return false` in the above, because what happens will vary depending on which way the function gets hooked up. Details: [*The Story on `return false`*](http://blog.niftysnippets.org/2011/11/story-on-return-false.html). – T.J. Crowder Sep 13 '13 at 11:22
  • @T.J.Crowder Can you tell me why and how the new way of setting up event handlers is better than the older onXYZ() attribute method. For example in the old way just by using inspect element I can see that clicking the button calls "removeDummy()" function, so it's easier to understand the flow of the codes logic. In the newer method I will have to open the javasccript file and search by the element's ID "btnRemoveDummy" just to find out which event listeners are working on it and which functions they call and in what order. For me this complicates the process of understanding the flow of code. – Ghos3t May 21 '18 at 10:30
  • 1
    @Ghos3t - A couple of ways: 1. Any function you call from an attribute-style handler has to be a global, and the global namespace is already Really Crowded™ and it's easy to pick a function name that conflicts with something else (this can be addressed by using an object with a likely-unique name and putting all your handlers on it, though). 2. Usine the old attribute-style way (or assigning to the `onxyz` property on the element) only allows a *single* handler, and if you assign to the property you replace whatever used to be there, so it doesn't play well with others. *(cont'd)* – T.J. Crowder May 21 '18 at 10:41
  • *(continuing)* There is also a faction who will say that mixing code and markup like that is a bad idea, but the last several years have seen the rise of frameworks/libs doing just that (but without the problems the old attribute handlers had), such as React and Angular and Marko and Knockout and... So that argument has less weight for me, but still a lot for some. – T.J. Crowder May 21 '18 at 10:43
40

Just do this element.remove();

Try it here LOOK

http://jsfiddle.net/4WGRP/

Muhammad Umer
  • 2,228
  • 2
  • 18
  • 17
  • 5
    Careful with this, as this seems to be a fairly new addition, and does not have full browser support namely IE and FF versions 22 and earlier (http://www.red-team-design.com/removing-an-element-with-plain-javascript-remove-method). – dule Sep 18 '13 at 18:45
  • 1
    I'd personally wait another 5 years to use this – slebetman Feb 19 '16 at 02:17
  • 2
    Well, this seems to be faily supported now: http://caniuse.com/#search=remove. I would accept to use it now. If you absolutely need to support IE11, I suppose a polyfill could easily be constructed... – jehon Jan 11 '17 at 14:37
  • 6
    Writing future-proof code is better than programming for the past. Save yourself the maintenance time, and use `.remove()` – Gibolt Aug 13 '17 at 21:13
9

You should use input type="button" instead of input type="submit".

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

Checkout Mozilla Developer Center for basic html and javascript resources

Nico Schlömer
  • 53,797
  • 27
  • 201
  • 249
Sandeep Kumar M
  • 3,841
  • 3
  • 38
  • 59
8

Your JavaScript is correct. Your button has type="submit" which is causing the page to refresh.

Pav
  • 2,288
  • 4
  • 22
  • 25
5

index.html

<input id="suby" type="submit" value="Remove DUMMY"/>

myscripts.js

document.addEventListener("DOMContentLoaded", {
//Do this AFTER elements are loaded

    document.getElementById("suby").addEventListener("click", e => {
        document.getElementById("dummy").remove()
    })

})
e-motiv
  • 5,795
  • 5
  • 27
  • 28
5

It reappears because your submit button reloads the page. The simplest way to prevent this behavior is to add a return false to the onclick like so:

<input type="submit" value="Remove DUMMY" onclick="removeDummy(); return false;" />
mVChr
  • 49,587
  • 11
  • 107
  • 104
4

Try running this code in your script.

document.getElementById("dummy").remove();

And it will hopefully remove the element/button.

Sim Reaper
  • 69
  • 3
4

Change the input type to "button". As T.J. and Pav said, the form is getting submitted. Your Javascript looks correct, and I commend you for trying it out the non-JQuery way :)

Newtang
  • 6,414
  • 10
  • 49
  • 70
  • I think I'll stick to submit because this is just an experimental exercise for my future projects that uses submit so I better get used to it... – Newbie Coder May 09 '11 at 06:20
3

That is the right code. What is probably happening is your form is submitting, and you see the new page (where the element will exist again).

alex
  • 479,566
  • 201
  • 878
  • 984
2

This works. Just remove the button from the "dummy" div if you want to keep the button.

function removeDummy() {
  var elem = document.getElementById('dummy');
  elem.parentNode.removeChild(elem);
  return false;
}
#dummy {
  min-width: 200px;
  min-height: 200px;
  max-width: 200px;
  max-height: 200px;
  background-color: #fff000;
}
<div id="dummy">
  <button onclick="removeDummy()">Remove</button>
</div>
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
Durtle02
  • 29
  • 1
1

I'm still a newbie too, but here is one simple and easy way: You can use outerHTML, which is the whole tag, not just a portion:

EX: <tag id='me'>blahblahblah</tag>'s innerHTML would be blahblahblah, and outerHTML would be the whole thing, <tag id='me'>blahblahblah</tag>.


So, for the example, if you want to delete the tag, it's basically deleting its data, so if you change the outerHTML to an empty string, it's like deleting it.
<body>
    <p id="myTag">This is going to get removed...</p>
    <input type="button" onclick="javascript:
        document.getElementById('myTag').outerHTML = '';//this makes the outerHTML (the whole tag, not what is inside it)
    " value="Remove Praragraph">
</body>

Instead, if you want to just not display it, you can style it in JS using the visibility, opacity, and display properties.

document.getElementById('foo').style.visibility = hidden;
//or
document.getElementById('foo').style.opacity = 0;
//or
document.getElementById('foo').style.display = none;



Note that opacity makes the element still display, just you can't see it as much. Also, you can select text, copy, paste, and do everything you could normally do, even though it's invisible.
Visibility fits your situation more, but it will leave a blank transparent space as big as the element it was applied to.
I would recommend you do display, depending on how you make your webpage. Display basically deleting the element from your view, but you can still see it in DevTools. Hope this helps!
HarryJamesPotter27
  • 181
  • 1
  • 1
  • 11