The code below creates a new button element with the text "Download" and an ID of "download", and appends it as a child element of the element with an ID of "container".
When the button is clicked the container's onclick is also triggered. I tried to remove it with
removeEventListener()
without success.
document.getElementById('download').removeEventListener("onclick", myclick);
document.getElementById('download').removeEventListener("click", myclick);
document.getElementById('download').removeEventListener("click", myclick, true);
function cleanup(elem) {
for (let t in elem) if (t.startsWith('on') && elem[t] != null) {
elem[t] = null;
console.log('cleanup removed listener from '+elem.nodeName,t);
}
for (let t of elem.all_handlers || []) {
elem.removeEventListener(t.typ, t.fn, t.opt);
console.log('cleanup removed listener from '+elem.nodeName,t.typ);
}
}
var el = document.getElementById('download');
cleanup(el);
I also tried all of those answers and none of them removed the onclick. (e.g. cloning etc.) PS: the HTML code cannot be modified because it's part of a framework.
$(document).ready(function() {
$('#container').append(
$(document.createElement('button')).prop({
type: 'button',
innerHTML: 'Download',
id : 'download'
})
);
// I placed the code to remove the event listener here
});
function myclick(e) {
console.log('myclick');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html id="container" onclick="myclick(event)">
</html>