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!

6
  • Use parentElement.insertAdjacentHTML(...) developer.mozilla.org/en-US/docs/Web/API/Element/… Commented Aug 25, 2022 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. Commented Aug 26, 2022 at 2:35
  • Why do you need beforeLastChild? Your example uses appendChild(). That's equivalent to beforeend. Commented Aug 26, 2022 at 2: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. Commented Aug 26, 2022 at 2:47
  • Find the last child, and call lastChild.insertAdjacentHTML('beforebegin', newHTML) Commented Aug 26, 2022 at 3:01

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.