Reputation: 7601
I have generate_uuid()
function that generates unique ids (originally retrieved from here):
function generate_uuid() {
return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
)
}
I have contentEditable
div
:
<div contenteditable>
<div id="48b62163-9f3b-4b20-8dad-dc99e27e1243">Edit text content here.<div>
</div>
When I add a new line to the text content, the html code becomes:
<div contenteditable>
<div id="48b62163-9f3b-4b20-8dad-dc99e27e1243">Edit text content here.<div>
<div id="48b62163-9f3b-4b20-8dad-dc99e27e1243">New line 1.</div>
</div>
As we notice, new div
is identical to the previously existing div
.
When I add more lines, the html code becomes:
<div contenteditable>
<div id="48b62163-9f3b-4b20-8dad-dc99e27e1243">Edit text content here.<div>
<div id="48b62163-9f3b-4b20-8dad-dc99e27e1243">New line 1.</div>
<div id="48b62163-9f3b-4b20-8dad-dc99e27e1243">New line 2.</div>
<div id="48b62163-9f3b-4b20-8dad-dc99e27e1243">New line 3.</div>
</div>
The same, new div
s are identical to the previously existing div
.
How could I customize the newly inserted div
s each time the user hits a line break? I want to make the id
attribute for a newly inserted div
be generated by the generate_uuid()
function. Something like this should be the result:
<div contenteditable>
<div id="48b62163-9f3b-4b20-8dad-dc99e27e1243">Edit text content here.<div>
<div id="0b0e3518-1fb2-43e4-9160-6563ac0f82be">New line 1.</div>
<div id="57d399c6-afa0-42ae-83c2-d6d7937f22d3">New line 2.</div>
<div id="1fe51cac-bb79-47e2-bd95-e813b33e29aa">New line 3.</div>
</div>
Upvotes: 1
Views: 104
Reputation: 13964
You could use a MutationObserver
to detect when a child is added and generate a dynamic id:
function uuid() {
return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
)
}
function subscriber(mutations) {
mutations.forEach(mutation => {
mutation.addedNodes.forEach(node => node.id = uuid());
console.clear();
console.log([...mutation.target.children].map(x => x.id));
});
}
const observer = new MutationObserver(subscriber);
observer.observe(document.querySelector('div[contenteditable]'), { childList: true });
<div contenteditable>
<div id="48b62163-9f3b-4b20-8dad-dc99e27e1243">Edit text content here.<div>
</div>
Upvotes: 2