skip to Main Content

I want to add eventlistener to a html element. But It creates js error when the element doesn’t exist. The element exists only on some pages.

    // (A) ATTACH CLICK LISTENER ON PAGE LOAD
window.addEventListener("load", () => {
  document.getElementById("download_mp3j_0").addEventListener("click", doSomething);
});
// (B) THE USUAL FUNCTION
function doSomething () {
  // (B1) DETACH CLICK LISTENER
  var div = document.getElementById("download_mp3j_0");
  div.removeEventListener("click", doSomething);
  // (B2) EXTRA - CHANGE THE TEXT IF YOU WANT
  div.innerHTML = "Downloading";
  // (B3) DO YOUR PROCESSING HERE
  alert("Downloading!");
  // (B4) RE-ENABLE AFTER PROCESSING IF YOU WANT
  // div.addEventListener("click", doSomething);
}

Basically, the function is to remove the button after it has been clicked, to avoid multiple redundant clicks.

I want the function doSomething to run only if the element download_mp3j_0 exists.

2

Answers


  1. Try this :

    if (document.getElementById("download_mp3j_0")) { // Check if the element exists
        // Add event listener
    }
    

    So it makes :

    // (A) ATTACH CLICK LISTENER ON PAGE LOAD ONLY IF THE ELEMENT EXISTS
    window.addEventListener("load", () => {
        if (document.getElementById("download_mp3j_0")) {
            document.getElementById("download_mp3j_0").addEventListener("click", doSomething);
        }
    });
    
    // (B) THE USUAL FUNCTION
    function doSomething() {
        // (B1) DETACH CLICK LISTENER
        var div = document.getElementById("download_mp3j_0");
        div.removeEventListener("click", doSomething);
        // (B2) EXTRA - CHANGE THE TEXT IF YOU WANT
        div.innerHTML = "Downloading";
        // (B3) DO YOUR PROCESSING HERE
        alert("Downloading!");
        // (B4) RE-ENABLE AFTER PROCESSING IF YOU WANT
        // div.addEventListener("click", doSomething);
    }
    
    Login or Signup to reply.
  2. Optional chaining operator

    A simple alternative would be to use the Optional chaining (?.) operator:

    .getElementById(id)?.addEventListener(...
    

    And the event handler is only attached when the element exists.

    You might also use the disable attribute during downloading as this would avoid having to add and remove the existing event handler.

    See code snippet for details

    window.addEventListener("DOMContentLoaded", function() {
    
      document.getElementById("download_mp3j_0")?.addEventListener("click", function() {
    
        let element = this;
        element.value = "Downloading...";
        element.disabled = true;
        element.style.cursor = "wait";
    
        // simulated download
    
        window.setTimeout(function() {
          element.value = "Download";
          element.disabled = false;
          element.style.cursor = "default";
        }, 2000);
    
      })
    });
    #download_mp3j_0 {
      background-color: steelblue;
      color: white;
    }
    
    #download_mp3j_0:disabled {
      background-color: orange;
    }
    <input type="button" id="download_mp3j_0" value="Download">
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search