14

I have an element that is added using javascript to my HTML document. I am trying to remove it when I click on that same element. I do not know the id of the element yet, I have just included a sample id for now.

I have already tried looking at this answer here (Creating an element that can remove it self?) and tried using the method provided here (Javascript: How to make a Control send itself in a method) as well to reference the element but have had no luck.

Here is what I have so far.

function remove() {
  var element = this.id;
  //I have also tried using document.getElementByID(this.id)
  element.remove();
  //I have also tried using element.parentNode.removeChild(element); to remove the element.
}
<div id="i" onclick="remove(this)">Sample text</div>

I am not sure what I am doing wrong but this is the error I keep getting.

"Uncaught TypeError: Cannot read property 'remove' of undefined"

kevinuulong
  • 530
  • 1
  • 4
  • 17
  • You are getting `this.id` and trying to remove that. It would be `this.remove()`, which won't work in IE, if you care. Also, you should learn to separate your JavaScript from your HTML. – StackSlave May 24 '19 at 00:35

9 Answers9

16

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>
Hassan Nemir
  • 472
  • 4
  • 9
7

Minimalist solution:

<div onclick="this.remove()">Sample text</div>
Sodj
  • 846
  • 11
  • 18
4

your remove function should be like this

function remove(elem){
  elem.parentNode.removeChild(elem);
}

your are passing a this in your html, which is the html tag itself, however, when you using this in your js function, that this is the function itself, so you will get error by trying to use the js function's id as element id

Jakub Kukul
  • 12,032
  • 3
  • 54
  • 53
lucas
  • 503
  • 2
  • 13
2

"Uncaught TypeError: Cannot read property 'remove' of undefined"

This means the object you're trying to remove doesn't exist what makes complete sense because this.id isn't defined anywhere.

To correctly reference a html element using javascript you need to use the document.getElementById() function. The id of the html element you're trying to remove is i - so try document.getElementById("i");

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

Another - more elegant way - is to pass a reference to the object you clicked on with the callback function. This is simply done by adding event as a parameter. Inside the callback you can reference the element using e.target.

function remove(e) {
  var element = e.target;
  element.remove();
}
<div id="i" onclick="remove(event)">Sample text</div>
obscure
  • 11,916
  • 2
  • 17
  • 36
2

To match your query, using outerHTML will remove the elements and his components from the DOM.

This require to use document.getElementById().

function remove(me) {
  document.getElementById(me).outerHTML = ""
}
<div id="i" onclick="remove(this.id)">Sample text</div>

A better coding practice, as the post is upvoted:

  • Using 3 chars for Id of elements is better

  • We can filter elements by type with target.nodeName, but the type need to be written in uppercase.

document.body.addEventListener("mousedown", function(e) {
  console.log(e.target.nodeName, e.target.id)
  if (e.target.nodeName === "DIV"){
    document.getElementById(e.target.id).outerHTML = ""
  }
}, false)
<body>
  <div id="el1">Sample text</div>
  <div id="el2">Sample text</div>
  <div id="el3">Sample text</div>
  <div id="el4">Sample text</div>
  <div id="el5">Sample text</div>
  <div id="el6">Sample text</div>
</body>
NVRM
  • 11,480
  • 1
  • 88
  • 87
0

If you want to use this in normal JS function you'll need to bind this to function. Else it'll default to window object, this in normal js points to window object. If you want to use this in to point to an object invoking the function then use ()=>{} arrow functions

function remove(element) {
   console.log(this) //will log Window Object
  //I have also tried using document.getElementByID(this.id)
  element.remove();
  //I have also tried using element.parentNode.removeChild(element); to remove the element.
}
<div id="i" onclick="remove(this)">Sample text</div>
Aditya Thakur
  • 2,562
  • 2
  • 10
  • 21
0

first grab your element:

const myDiv = document.querySelector('div');

then add click event listener to it, so when it gets clicked on, the callback method gets invoked, where 'e.target' acts as 'this', and finally remove it using remove():

myDiv.addEventListener('click', function(e){
  e.target.remove();
});
-1

Don't use inline event listeners (the one on the button in this example is only for simplification).

function createDiv() {
  let div = document.createElement('div');
  div.textContent = `Sample text, created on ${new Date()}`;
  div.addEventListener('click', remove);
  document.body.appendChild(div);
}

function remove(e) {
  e.target.remove();
}
<button type="button" onclick="createDiv()">Add a div</button>

If you cannot access the element for adding a listener, you can also use a delegate listener:

document.addEventListener('click', remove);

function remove(e) {
  // you need some check here if you don't want any element to be removed on clicking it
  e.target.remove();
}
<div>foo</div>

<div>Sample text</div>
connexo
  • 53,704
  • 14
  • 91
  • 128
-1

I would do something like this, so your JavaScript and CSS are cached. Just make sure you change your filenames when updating your files upon deployment (when people know your site exists).

//<![CDATA[
/* external.js */
var doc, bod, M, I, S, Q;// for use on other loads
addEventListener('load', function(){
doc = document; bod = doc.body;
M = function(tag){
  return doc.createElement(tag);
}
I = function(id){
  return doc.getElementById(id);
}
S = function(selector, within){
  var w = within || doc;
  return w.querySelector(selector);
}
Q = function(selector, within){
  var w = within || doc;
  return w.querySelectorAll(selector);
}
function remove(e){
  e.parentNode.removeChild(e);
}
var sample = I('sample');
sample.onclick = function(){
  remove(this);
}
}); // end load
//]]>
/* external.css */
*{
  box-sizing:border-box; padding:0; margin:0;
}
html,body{
  width:100%; height:100%;
}
body{
  background:#ccc;
}
#content{
  padding:7px;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
  <head>
    <meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1' />
    <title>Test Template</title>
    <link type='text/css' rel='stylesheet' href='external.css' />
    <script type='text/javascript' src='external.js'></script>
  </head>
<body>
  <div id='content'>
    <div id='sample'>Sample Text</div>
  </div>
</body>
</html>
StackSlave
  • 10,613
  • 2
  • 18
  • 35