Is there a way to protect these child elements from being deleted?
Unfortunately, preventing the deletion of these child elements is not possible. However, here is an alternative approach.
Example:
Given that direct children cannot be retained, we will need to create two distinct elements instead.
<div class="editor">
<label class="editor-label">You can't delete me</label>
<div class="editor-area" contentEditable="true"></div>
</div>
Eventually, eliminate the label from the flow to prevent any interference with the area.
.editor {
border: solid 1px #CCC;
position: relative; // Establishing context for label
line-height: 1.5;
}
.editor-area {
min-height: 100px;
padding: 5px;
}
.editor-label {
position: absolute; // Exclusion from the flow
margin: 5px 0 0 5px;
user-select: none;
}
Lastly, to ensure the caret begins after the text in the label, determine its width and assign it to the text-indent
value of the area.
var editorLabel = document.querySelector('.editor-label');
var editorArea = document.querySelector('.editor-area');
var editorLabelRect = editorLabel.getBoundingClientRect();
editorArea.style.textIndent = editorLabelRect.width + 'px';
editorArea.innerHTML = ' ';
Finalized code:
var editorLabel = document.querySelector('.editor-label');
var editorArea = document.querySelector('.editor-area');
var editorLabelRect = editorLabel.getBoundingClientRect();
editorArea.style.textIndent = editorLabelRect.width + 'px';
editorArea.innerHTML = ' ';
.editor {
border: solid 1px #CCC;
position: relative;
line-height: 1.5;
}
.editor-area {
min-height: 100px;
padding: 5px;
}
.editor-label {
position: absolute;
margin: 5px 0 0 5px;
user-select: none;
}
<div class="editor">
<label class="editor-label">You can't delete me</label>
<div class="editor-area" contentEditable="true"></div>
</div>