Search code examples
javascriptevent-delegation

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>


Solution

  • 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>