Link to remove an element in JavaScript

Let's have a paragraph. Let's make a link next to it, with the help of which this paragraph can be deleted.

Let's implement:

<div id="parent"> <p id="elem">text</p> <a href="#" id="remove">remove</a> </div> let elem = document.querySelector('#elem'); let remove = document.querySelector('#remove'); remove.addEventListener('click', function() { elem.remove(); });

Note that the link has a # in the href attribute. If this hash is removed, we will get a link transition and, as a result, a page refresh.

In fact, the deletion of the paragraph will also occur, but we will not notice this, since the page will be refreshed and everything will return to its original state.

To solve the problem, you need to prevent following the link with preventDefault:

<div id="parent"> <p id="elem">text</p> <a href="" id="remove">remove</a> </div> let elem = document.querySelector('#elem'); let remove = document.querySelector('#remove'); remove.addEventListener('click', function(event) { elem.remove(); event.preventDefault(); // cancels the link transition });

On your own, without looking into my code, solve the described problem.

enru