Let's say I have an element that I want to write the html of, for example:
const tr = ...;
tr.innerHTML = `<td>...</td>`;
Is there a way to write the html so that I have an event listener already on it, or do I need to use a new selector and add the event listener to it, such as with:
tr.querySelector('td').addEventListeneer('click', myFunction);
Or how is this normally done?
CodePudding user response:
You can write a Function that takes a template String as input:
const dom = innerString => {
const holder = document.createElement("DIV");
holder.innerHTML = innerString;
return holder.children;
};
Then call it with
const elements = dom("<tr><td>…</td></tr>");
Now you can attach an event listener to the first element with
elements[0].children[0].addEventListener(…);
Then append the elements array to the document
CodePudding user response:
You can do it as you suggest, by inserting the HTML and then adding an event listener.
Alternatively you could use the createElement document method to create the element outside of the DOM, attach your event listener and any other properties and then insert it as a whole.
There are performance and security benefits from doing this the second way, but it largely depends on the use case, so feel free to explore this further if this is of importance to you.