0

I need a function like this:

document.getElementsByTagName("div").addEventListener("mouseover", mouseOver);

function mouseOver() {
document.getElementsByTagName("div").remove;
}
<div style="width: 100px; height: 100px; background-color: red; position: absolute"></div>

So I have to select tag names and remove them on mouseover. How is it possible to code this?

LauraPL
  • 1
  • 2
  • Aside from the [issue addressed by the linked question](https://stackoverflow.com/questions/10693845/what-do-queryselectorall-and-getelementsby-methods-return), within your handler use `this` to access the element related to the event. (Or accept the event object parameter and use `event.currentTarget`.) Also, to call a function, you need `()` after the name. – T.J. Crowder Oct 28 '19 at 11:24
  • @T.J.Crowder I don't think its a duplicate. I have to work with pure JavaScript. And I really don't understand it. What exactly is missing? – LauraPL Oct 28 '19 at 11:32
  • Yes, the main issue above is a duplicate of that question. (I don't see why you're mentioning "pure JavaScript," there aren't any libraries or similar used in that other question.) You need to loop through the collection, which you aren't above; see that question's answers for details. Then, in addition, you need to do the things I described above. – T.J. Crowder Oct 28 '19 at 11:38
  • For instance: `function mouseOver() { this.parentNode.remove(this); } var list = document.getElementsByTagName("div"); for (var i = 0; i < list.length; ++i) { list[i].addEventListener("mouseover", mouseOver); }` (There are shorter ways on modern browsers; that code will work all the way back to IE9.) On modern browsers: `function mouseOver() { this.remove(); } document.querySelectorAll("div").forEach(function(div) { div.addEventListener("mouseover", mouseOver); });` – T.J. Crowder Oct 28 '19 at 11:40
  • @T.J.Crowder I will have more than one div and only want to remove the hovered ones. With your code everything removes ... – LauraPL Oct 28 '19 at 12:07
  • Stupid typo on my part in the first example, should be `this.parentNode.removeChild(this);` **not** `this.parentNode.remove(this);`: https://jsfiddle.net/tjcrowder/0bm1ckqj/ – T.J. Crowder Oct 28 '19 at 12:15

1 Answers1

0

Actually, you already have solution. You just need to fix your callback to call remove method:

function mouseOver(event) {
  event.target.remove();
}
Andres
  • 967
  • 6
  • 7
  • Thank you for your answer. It does not work how I tried it now :/ Could you give a full code answer? – LauraPL Oct 28 '19 at 11:29