skip to Main Content

How to remove encircle element using javascript without target id or class????
Like that

<div>
  Choice 1 <span>close X</span>
</div>

I hope that when someone click the "close X" word, it will delete Choice 1 and close X

I try to

    <div>
          Choice 1 <span onclick="remove(this)">close X</span>
    </div>
    <script>
    function remove(val) {
      //val.remove();   Just remove the "close X" word
      //val.previousElementSibling.remove();   //Not work
      //$(this).prev().remove();   using Jquery //Still Not work
    }
    </script>

Anyidea How to do it?? Thank you very much

2

Answers


  1. Try event.target.parentElement.remove()

    function remove(event) {
      event.target.parentElement.remove();
    }
    <div>
      Choice 1 <span onclick="remove(event)">close X</span>
    </div>
    Login or Signup to reply.
  2. Basically, use the addEventListener() method on the "Close X" element to capture clicks then iterate over the child nodes of the parent <div> element then remove any text nodes found.

    const el = document.getElementById("element");
    const close = document.getElementById("close");
    
    close.addEventListener("click", () => {
      [...el.childNodes].forEach(child => child.nodeType === 3 && child.remove());
      console.log("Other functions after removing all text can be run here.");
    });
    <div id="element">
      Choice 1 <span id="close">close X</span>
    </div>

    You can actually shorten it a bit by using some arrow functions.

    const el = document.getElementById("element");
    const close = document.getElementById("close");
    
    close.addEventListener("click", () => ([...el.childNodes].forEach(child => child.nodeType === 3 && child.remove()), console.log("Other functions after removing all text can be run here.")));
    <div id="element">
      Choice 1 <span id="close">close X</span>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search