Home > other >  How could I click any html element and it would just delete/remove itself with javascript?
How could I click any html element and it would just delete/remove itself with javascript?

Time:01-03

been working on a thing for fun. I was wondering how I could delete an html element if I just clicked it on any website or html file. No jquery or other libraries, just vanilla JS. If the question is hard to understand here's an example: -Website loads -I see a p tag or img tag or just any tag and I don't want to see it any more so I just click it and it deletes. -I'm now happy because of what I've done.

currentCode:

window.addEventListener("click", function(i) {
  //Code to remove something? idk... Not that good with js atm...
}, false);```

CodePudding user response:

window.addEventListener("click", function(e) {
  const target = e.target;
  target.remove();
}, false);
<button>a</button>
<button>a1</button>
<p>paragraph...</p>
<h1>header...</h1>

CodePudding user response:

Here are two ways to achieve the same effect:-

document.getElementById("myDIV").style.display = "none"; // hides element

document.getElementById("myDIV").remove(); // removes element from the DOM

CodePudding user response:

What about setting the element's display to none?

const foo = document.getElementById('foo');
const bar = document.getElementById('bar');

[foo, bar].forEach((el) => {
  el.addEventListener('click', () => el.style.display = 'none');
});
<div id="foo" style="border: 1px solid black; height: 50px; margin-bottom: 20px;"></div>
<div id="bar" style="border: 1px solid red; height: 50px;"></div>

EDIT: This time without IDs (this is a good intro to event bubbling):

// Look ma, no ids!
window.addEventListener('click', (event) => {
  event.target.style.display = 'none';
});
<div id="foo" style="border: 1px solid black; height: 50px; margin-bottom: 20px;"></div>
<div id="bar" style="border: 1px solid red; height: 50px;"></div>

CodePudding user response:

You can try something like this Remove Element

CodePudding user response:

If you want to delete something that you don't want to see with a click event, you can use the style attribute.

Here is the js script you can use :

<script>
    window.addEventListener("click", function(e) {
        e.target.style = "display: none;";
    });
</script>
  • Related