Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

122
Views
Setting .outerHTML clears all .innerHTML element contents

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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);
})()

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!