Home > front end >  How to delete or empty an HTML element selected through function parameter?
How to delete or empty an HTML element selected through function parameter?

Time:12-07

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?

CodePudding user response:

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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.

  • Related