I have a bunch of list items that need to have tags, classes, and all that. I'm getting the JSON data from the server and building the li items up using appendChild on a ul.
Here's an example function from for building the "lemma" items.
function createLemmaItem(lemma) {
// bunch of "lemma" attributes -- create the base li
let total = lemma.forms.length;
let node = document.createElement("li");
node.classList.add("lemma-item");
node.dataset.lemmaId = lemma.id;
node.dataset.group = lemma.group;
node.setAttribute("onclick", "activateLemma(this)");
// set the innerHTML to a long HTML string
node.innerHTML = `
<div class="lemma-col-1">
<label>
<input type="checkbox" onclick="lemmaToggleAll(this)" checked>
${lemma.name}
</label>
</div>
<div class="lemma-col-2">
${lemma.latin}
</div>
<div class="lemma-col-3">
${lemma.homid}
</div>
<div class="lemma-col-4">
<span class="counter">(<span class="total">${total}</span>/<span class="max">${total}</span>)</span>
</div>`;
return node;
}
Another example for a "form" item:
function createFormItem(lemma, form) {
let node = document.createElement("li");
node.classList.add("form-item");
node.classList.add("hidden");
node.dataset.lemmaId = lemma.id;
node.dataset.group = lemma.group;
node.innerHTML = `
<label>
<input type="checkbox" name="${lemma.name}@${lemma.latin}@${lemma.homid}@${lemma.group}@${form}" onchange="changeCount(this)"checked>
${form}
</label>`
return node;
}
Then I create the items by using this function to generate each one and then appending it to a ul with appendChild.
This seems pretty messy to me, and gets even messier when I have longer HTML strings. I'm concerned about the readability, maintainability, and fragility of my code when I do it this way.
How do you usually handle long HTML strings like this that are in the middle of JS files (without using a framework)? Is there a canonical way? Put the strings in a separate file or something?