HTML:
<tr id="row1" data-Source="{{row_id}}">
<td><input id="chk1" class="chk" type="checkbox"></td>
<td><input id="chk2" class="chk" type="checkbox"></td>
<td><input id="chk3" class="chk" type="checkbox"></td>
</tr>
JavaScript:
(() => {
document.getElementById("chk1").checked = true;
let insertTR = document.getElementById("row1").cloneNode(true);
let elems = insertTR.querySelectorAll(".chk");
for (let i = 0; i < elems.length; i++) {
elems[i].checked = true;
}
document.getElementById("theTable").appendChild(insertTR);
})()
The JS spec says that I cannot access an element's .outerHTML while it is not attached to the DOM body, and in fact, I get an error in the attempt to set the .outerHTML.
So:
document.getElementById("theTable").appendChild(insertTR);
insertTR.outerHTML = insertTR.outerHTML.replace("{{row_id}}","myRowId");
That works fine to take care of the TR's {{row_id}} tag, but now, my previously checked checkbox is now unchecked.
Mozilla docs (https://developer.mozilla.org/en-US/docs/Web/API/Element/outerHTML) say:
"Setting the value of outerHTML replaces the element and all of its descendants with a new DOM tree constructed by parsing the specified htmlString."
So, how can I accomplish this?
Replace the string of the HTML before you make it into an element and append it. –
function elemFromString(html) {
var dummy = document.createElement("div");
dummy.innerHTML = html.trim();
if (dummy.children.length > 1) {
console.error("expecting one wrapping element for html. will return only firstChild")
}
var result = dummy.firstChild;
result.parentNode.removeChild(result)
return result;
}
(() => {
document.getElementById("chk1").checked = true;
let insertTR_html = document.getElementById("row1").outerHTML;
insertTR_html = insertTR_html.replace("this", "that");
let insertTR = elemFromString(insertTR_html);
let elems = insertTR.querySelectorAll(".chk");
for (let i = 0; i < elems.length; i++) {
elems[i].checked = true;
}
document.getElementById("theTable").appendChild(insertTR);
})()