How can I add an onclick event to an HTMLAnchorElement?

I’m working on an ionic app. As a part of this app, I’m sending a get request and get an html page. Now, I need to present it in my app. I’ve tried to present it in an iframe using the srcdoc but the web page has links to another pages and when it is being clicked I need to provide an Authorization header. Therefore I decided I should take the html string and manipulate it so when the anchor is being clicked it will call a function and send a get request with the authorization head (to the href url)

I’m converting my html string to a Document object and get all the “a” items:

var doc = (new DOMParser).parseFromString(this.htmlPage, “text/html”);
var links = doc.body.getElementsByTagName(“a”);
for (let i = 0; i < links.length; i++) {
const element = links.item(i);
var self = this;
element.onclick = function() {
self.redirect(element.href);
};
element.removeAttribute(“href”);
}

The href attribute is being removed but the onclick event is not added. How can I fix it?