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

165
Views
why remove function is not working in event delegation in javascript?

I want to remove h1 tag when clicked on refresh btn but it doesn't remove h1 tag but when i run same code by using addeventlistener on each btn it run. but not run in delgation .

var wrapper = document.querySelector(".wrapper");

wrapper.addEventListener("click", function(e) {
  var currentYear = 2018;
  var h1 = document.createElement("h1");
  if (e.target.id === "btn") {
    var data = document.getElementById("age").value
    var output = currentYear - data;
    h1.innerText = output + "  year old";
    age.after(h1)
  }
  if (e.target.id === "dlt") {
    var data = document.getElementById("age").value = null;
    h1.remove();
  }
}, false);
<div class="wrapper">

  <h1>ENTER YOUR AGE</h1>
  <input type="text" id="age">
  <button id="btn">Get Age</button>
  <button id="dlt">Refresh</button>

</div>

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

0

Here is a modernized (es20xx) and somewhat streamlined version of your code. The handling is moved to a separate function. See comments within the snippet for explanation.

document.querySelector(`.wrapper`).addEventListener("click", handleWrapper);

function handleWrapper(e) {
  const currentYear = 2018;
  let h1Result = e.target.closest(`.wrapper`).querySelector(`#result`);
  console.clear();
  
  // Get Age
  if (e.target.id === `btn`) {
    const createH1 = () => {
      // use insertAdjacentHTML to create H1#result
      document.querySelector(`.wrapper`).insertAdjacentHTML( `beforeend`, `
        <h1 id="result"></h1>` );
      //    ^ enable finding *this* h1, not the original  
      // return the newly create element  
      return document.querySelector(`.wrapper h1#result`);
    };
    
    let data = +document.querySelector("#age").value.trim();
    //           ^ convert to Number
    
    data = isNaN(data) || !data ? 0 : data;
    //     ^ if conversion failed, or no data, set data to 0

    // if [h1Result] is non existing create it using  
    // the createH1 function expression and set the result 
    // of the found or created element.
    // *Note: I took the liberty to call it the birth year, 
    // because that seems to be goal here.
    (h1Result || createH1()).textContent = `Birth year: ${currentYear - data}`;
  }
  
  // Refresh
  if (e.target.id === `dlt`) {
    // empty input
    document.querySelector(`#age`).value = ``;
    
    // remove the result if it exists
    if (h1Result) {
      h1Result.remove();
    }
  }
}
<div class="wrapper">
  <h1>ENTER YOUR AGE</h1>
  <input type="text" id="age">
  <!-- did you mean: get birth year? -->
  <button id="btn">Get Age</button>
  <button id="dlt">Refresh</button>
</div>

about 4 years ago · Juan Pablo Isaza Report

0

Instead of creating a h1 element, you should find it.

So replace:

var h1 = document.createElement("h1");

with

var h1 = document.querySelector("h1");

But then make sure to create a new h1 whenever it is not found, and to insert it into the document in the first if block. It might be better to just hide and show it.

There seems also to be a mixup between birth year and age: either the user should enter their year of birth and they get the age, or vice versa.

Finally, remove the assignment to data in the second if block: it serves no purpose.

Proposed snippet:

var wrapper = document.querySelector(".wrapper");
var h1 = document.querySelector("h1");

wrapper.addEventListener("click", function(e) {
  var currentYear = 2018;
  if (e.target.id === "btn") {
    var data = document.getElementById("age").value
    var output = currentYear - data;
    h1.innerText = output + "  year old";
    h1.classList.remove("hidden");
    age.after(h1)
  }
  if (e.target.id === "dlt") {
    h1.classList.add("hidden");
    document.getElementById("age").value = null;
    h1.remove();
  }
}, false);
.hidden { display: none } 
<div class="wrapper">

  <h1>Enter your Year of Birth</h1>
  <input type="text" id="age">
  <button id="btn">Get Age</button>
  <button id="dlt">Refresh</button>

</div>

about 4 years ago · Juan Pablo Isaza Report

0

You can set attributes while creating elements and delete them using attributes.

var wrapper = document.querySelector(".wrapper");

wrapper.addEventListener("click", function(e) {
  var currentYear = 2018;
  var h1 = document.createElement("h1");
  h1.setAttribute("id", "title")
  if (e.target.id === "btn") {
    var data = document.getElementById("age").value
    var output = currentYear - data;
    h1.innerText = output + "  year old";
    age.after(h1)
  }
  if (e.target.id === "dlt") {
    var data = document.getElementById("age").value = null;
    document.getElementById("title").remove()
  }
}, false);
<div class="wrapper">

  <h1>ENTER YOUR AGE</h1>
  <input type="text" id="age">
  <button id="btn">Get Age</button>
  <button id="dlt">Refresh</button>

</div>

I suggest a few clean-ups. You can use display style to do your show hide.

const btn = document.querySelector(".wrapper .btn");
const dlt = document.querySelector(".wrapper .dlt");
const input = document.querySelector(".wrapper input");
const title = document.querySelector(".wrapper .title");
title.style = "display:none";

btn.addEventListener("click", () => {
  const currentYear = 2018;
  const output = currentYear - input.value;
  console.log(output)
  title.innerText = output + "  year old";
  title.style = "display:block"
})
dlt.addEventListener("click", () => {
  input.value = "";
  title.style = "display:none";
})
<div class="wrapper">

  <h1>ENTER YOUR AGE</h1>
  <input type="text">
  <h1 class="title">Get Age</h1>
  <button class="btn">Get Age</button>
  <button class="dlt">Refresh</button>
</div>

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!