How can I clone a new row without also copying the text that has been inserted inside the contenteditable div? I want a new blank div to type into. Many thanks
<div id="wrapper">
<div id="row">
<div id="left">
<p><strong>Heading</strong></p>
<div contenteditable="true" data-placeholder="Type here...">
</div>
<div id="right">
<p><strong>Heading</strong></p>
<div contenteditable="true" data-placeholder="Type here...">
</div>
</div>
</div>
<button id="button" onlick="duplicate()">Add another row</button>
document.getElementById('button').onclick = duplicate;
var i = 0;
var original = document.getElementById('row');
function duplicate() {
var clone = original.cloneNode(true);
clone.id = "row" i;
original.parentNode.appendChild(clone);
}
CodePudding user response:
You need to select the contenteditable elment and replace the html
function duplicate() {
var clone = original.cloneNode(true);
clone.id = "row" i;
clone.querySelector('div[contenteditable="true"]').innerHTML = '';
original.parentNode.appendChild(clone);
}
CodePudding user response:
Just use the DOM API with its amazing document.createElement
:
const btn = document.getElementById('addRow');
const rowContainer = document.getElementById('row');
btn.addEventListener('click', function() {
const newDiv = document.createElement('div');
newDiv.contentEditable = true;
rowContainer.appendChild(newDiv);
});
[contenteditable=true] {
border: 1px solid #999;
}
<div id="wrapper">
<div id="row">
<p><strong>Heading</strong></p>
<div contenteditable="true" data-placeholder="Type here..."></div>
</div>
</div>
<button id="addRow">Add another row</button>