0
<div class="bank" id="savingsAcc0">
    <div class="deleteAccButton deleteSavings">
        <p>-</p>
    </div>
    <input type="text">
    <input type="text">
</div>

I am trying to duplicate the above HTML into an already loaded DOM using Javascript. Because I am trying to do this with an already loaded DOM I cannot use document.write(). One option is to do the follow:

function nodeWantingToDuplicate() {
    parentDiv = document.createElement("div");
    parentDiv.class = "bank";
    parentDiv.id = "savingsAcc0";
    childDiv = document.createElement("div");
    childDiv.class = "deleteAccButton deleteSavings";
    childP = createElement("p");
    childInput = document.createElement("input");
    childInput.type = "text";
    // then assemble elements using .appendChild, etc.
    return parentDiv;
}

But I am looking for something more simple, kind of like the follow:

// of course, you cannot use .createElement() in this way.
nodeWantingToDuplicate = document.createElement("<div class='bank' id='savingsAcc0'><div class='deleteAccButton deleteSavings'><p>-</p></div><input type='text'><input type='text'></div>");
parentElement.appendChild(nodeWantingToDuplicate);

The HTML can look messing. It is the Javascript I want looking clean. Please Advise. Thank you so much!

cwcv2009
  • 11
  • 4
  • Use `parentElement.insertAdjacentHTML(...)` https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML – Barmar Aug 25 '22 at 17:49
  • `parentElement.insertAdjacentHTML(position, text)` would work perfectly, if "beforeLastChild" was an argument option for the **position** parameter. Inserting **nodeWantingToDuplicate** before the last child must be the case otherwise I must significantly change the CSS and HTML layout. – cwcv2009 Aug 26 '22 at 02:35
  • Why do you need beforeLastChild? Your example uses `appendChild()`. That's equivalent to `beforeend`. – Barmar Aug 26 '22 at 02:38
  • You are correct. I made a mistake in my question. I should have specified the importance that the child be appended before the last child. Knowing `.insertAdjacentHTML(position, text)` does bring me closer to a solution. – cwcv2009 Aug 26 '22 at 02:47
  • Find the last child, and call `lastChild.insertAdjacentHTML('beforebegin', newHTML)` – Barmar Aug 26 '22 at 03:01
  • And that will work. In fact, doing it that way will allow me to reduce my js code even further. I really appreciate it! – cwcv2009 Aug 26 '22 at 03:20

0 Answers0