innerHTML question from Known Issues documentation

The Known Issues documentation states the following:

When applying HTML using innerHTML , event handlers and scripts are currently parsed in Photoshop, but not in XD. DO NOT RELY ON THIS BEHAVIOR , as it will likely go away in the future and match XD’s behavior (which is by design).

I’d like to get a little clarification on this. I use innerHTML to generate a list on my plugin.

Once the list is created, I then use the following code to access these list elements:

var listElements = document.getElementById("divMyList").querySelectorAll("li");

I then go on to to use listElements array to create eventLstteners:

listElements.forEach(el => el.addEventListener('click', event => { //do stuff when clicked}))

Does the “Known Issue” quoted above mean this will no longer work in the future?

This known issue refers to trying to do this:

someElement.innerHTML = `<ul>
  <li onclick="callSomeJS()">Click Me</li>
</ul>`;

The above only works in Ps when allowCodeGenerationFromStrings is true. This was accidentally defaulted to true for PS Manifest v4, but XD has always had this set to false. With Manifest v5, the default is unified as false for all host apps.

Your particular example – where you’re adding event listeners from JS – is OK – you’re attaching events from JS, not from HTML.

That said, I’ll note that there’s one better way to do what you’re doing – and that’s to apply a single event listener on #divMyList, like so:

document.getElementById("divMyList").addEventListener("click", evt => {
    const clickedElement = evt.target;
    if (clickedElement.tagName !== "LI") return;
    /* now do your stuff when LI is clicked -- 
       if you need to know more about which one 
       was clicked, I like to use "data" attributes.
       e.g., 
           <li data-which="this"></li>
           <li data-which="that"></li>
    */
    const which = clickedElement.dataset.which;
    console.log(which); /*this or that, depending on which was clicked*/
});

The more event handlers you have on a page, the slower event handling will become and your plugin will require more memory as well. If your list stays small, probably no big deal, but if your list had 100 items in it… that would start to add up.

1 Like

Thanks for that info, @kerrishotts. Now I understand this better and it all makes sense. I’ll work on adding just one event listener per list.