Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

278
Views
How to delete or empty an HTML element selected through function parameter?

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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

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>

about 4 years ago · Juan Pablo Isaza Report

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!