0

I am trying to delete or empty the element using JAVASCRIPT, but it must be the element we pass into the function as a parameter. It has to work onClick for example, everything has to work dynamically, but I can't get it to work. Here is my code so far:

function deleteElement(selector, type) {
  switch (type) {
    case `${"delete" || "remove"}`:
      document.querySelector(selector).remove();
      break;
    case "empty":
      document.querySelector(selector).innerHTML = "";
      break;

    // if user doesn't enter desired outcome, the element will be deleted by default
    default:
      document.querySelector(selector).remove();
      break;
  }
}

My question is, using this code how can I perform action on dynamically selected element?

  • change that first case to `case 'delete': case 'remove':` (on 2 separate lines) – Kinglish Dec 06 '21 at 21:35
  • `case '${"delete" || "remove"}':` would just be `case "delete":`, see https://stackoverflow.com/questions/6513585/test-for-multiple-cases-in-a-switch-like-an-or – skara9 Dec 06 '21 at 21:38
  • I get that, but the problem is my selector, how do I for example execute my code when I click on a div, without adding event listener directly into the function – adimustafyc Dec 06 '21 at 21:39
  • You don't need a listener for this. You're executing it manually via a function. – Kinglish Dec 06 '21 at 21:49

2 Answers2

0

If you want to remove the element without using a selector when its triggered you can pass this as the parameter instead of selector:

function removeEl(element){
  element.remove();
}
<div onclick="removeEl(this)">click</div>

If you want to have an event listener for all of the divs sharing a same class/attribute/parent ... you can do it like this: (in this example the shared selector between your elements is div[data-type])

// looping thourgh all 'div's having a 'data-type' attribute
document.querySelectorAll('div[data-type]').forEach(element =>
  // adding a simple onclick event listener
  element.onclick = () => element.remove()
)
<div data-type="hi">Hey</div>
<div data-type="type">Yes sir</div>
Ke1vans
  • 106
  • 7
0

I am pretty sure there must be a more elegant solution, but if you really require a listener, you could do something like this:

clickable.addEventListener("click",(selector, type) => {deleteElement('section')});

where clickable is a DOM-element you can set with a querySelector.