The following code relies on the fact that on new line the browser duplicates the last child element of the editable div. On key down we handle the case when there are no children yet, and we make sure that the first element will be a paragraph, letting the browser create more paragraphs automatically.
To set the id and name of newly created paragraphs we use the mutation observer API to get notified when a paragraph is added.
Another peculiarity is the second paragraph that we add if the first keystroke is Enter. We need this because the browser displays an empty div and a div with one empty paragraph identically.
<html>
<head>
<script>
function loaded()
{
// https://stackoverflow.com/questions/105034/how-to-create-guid-uuid
function uuidv4() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
const zzz = document.getElementById("zzz");
zzz.onkeydown = function(e)
{
if(!zzz.children.length)
{
let element = document.createElement("p");
element.innerHTML = "<br />";
zzz.appendChild(element);
if(e.code == "Enter")
{
element = document.createElement("p");
element.innerHTML = "<br />";
zzz.appendChild(element);
}
window.getSelection().collapse(element, 0);
e.preventDefault();
}
}
const observer = new MutationObserver(function(mutationList, observer)
{
for(let ilength = mutationList.length, i = 0; i < ilength; ++i)
{
const addedNodes = mutationList[i].addedNodes;
for(let jlength = addedNodes.length, j = 0; j < jlength; ++j)
{
const node = addedNodes[j];
const randomNumber = uuidv4();
node.id = "pid" + randomNumber;
node.setAttribute("name", "pn" + randomNumber);
}
}
});
observer.observe(zzz, { childList: true });
}
</script>
</head>
<body onload="javascript:loaded();">
<div id="zzz" contenteditable="true"></div>
</body>
</html>