Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
24
rated 0 times [  28] [ 4]  / answers: 1 / hits: 66260  / 5 Years ago, fri, may 24, 2019, 12:00:00

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



More From » html

 Answers
17

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>




[#52082] Thursday, May 16, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
breap

Total Points: 606
Total Questions: 96
Total Answers: 108

Location: Djibouti
Member since Sun, Feb 27, 2022
2 Years ago
breap questions
Thu, Jun 24, 21, 00:00, 3 Years ago
Wed, Mar 18, 20, 00:00, 4 Years ago
Mon, Oct 7, 19, 00:00, 5 Years ago
;