[SalesForce] Onclick handler doesn’t fire in dynamically-added dom element

The interface for my Lightning component is a very dynamic table that must be built according to data that is retrieved from a remote source. To create this table, inside of my helper class, I'm using the standard javascript functions (createElement(), appendChild(), etc.). I then look up my main div element (which was defined in the component markup in the usual way: ) and append the table to it via appendChild().

Inside the table, I am creating a link element with something like the following code:

var docTable = component.find("docTableCont").getElement(); // standard div devined in component markup
var aLink= document.createElement('a');
aLink.setAttribute("onclick", "alert('hello'); sforce.console.getEnclosingPrimaryTabId(function(result){ sforce.console.openSubtab(result.id, " + myCustomURL + ", true);}); return false;");
aLink.setAttribute("href", "#");
var txtLabel = document.createTextNode("View");
aLink.appendChild(txtLabel);
docTable.appendChild(aLink);

As you can see, I'm trying to open 'myCustomURL' in a new subtab. However, my onclick handler is never getting called — also notice that I added an alert('hello') to the handler code so that I can know if the handler is being called — no 'hello' alert is ever generated when clicking on the link.

I've done a good bit of searching and I see that I can add event handlers in my helper class but those handlers never get called either. I'm guessing that my problem is that my handlers are getting over-ridden by some low-level code in the framework. However, I can't find a better way to create dom elements in such a dynamic way. I also can't find a more documented method for opening a URL in a subtab than by using the sforce.console library.

Best Answer

I was able to get something to work by calling addEventlistener rather than setting an attribute. However, I wasn't able to add a regular Lightning controller function via component.getReference() - I'm going to investigate that further.

However, for now, this should work as long as the sforce.console is defined (I would have thought it wouldn't be available, but I haven't worked with the console and lightning, so I really can't speculate on this).

Here's what I got to work:

var docTable = component.find("docTableCont").getElement(); 
var aLink = document.createElement('a');

aLink.addEventListener("click", function(){alert("test");});
aLink.setAttribute("href", "#");

var txtLabel = document.createTextNode("View");
aLink.appendChild(txtLabel);

docTable.appendChild(aLink);