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
Try this :
So it makes :
Optional chaining operator
A simple alternative would be to use the Optional chaining (?.) operator:
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