Я тоже сделал:
function headerFormatter(arg) {
let newTag = document.createElement(arg);
if (window.getSelection) {
let sel = window.getSelection();
if (sel.rangeCount) {
let range = sel.getRangeAt(0).cloneRange();
// create an object from range for querying tags
let rangeProxy = sel.getRangeAt(0).cloneContents();
if (
rangeProxy.querySelector('h1') ||
rangeProxy.querySelector('h2') ||
rangeProxy.querySelector('h3')
) {
let tagContent = rangeProxy.querySelector(arg).innerHTML;
// compare selection length with queried tag length
if (range.startOffset == 1) {
tagContent = tagContent.replace(/(<([^>]+)>)/ig, "");
range.deleteContents();
range.insertNode(document.createTextNode(tagContent));
sel.removeAllRanges();
sel.addRange(range);
return;
}
else {
let rangeToString = range.toString().replace(/(<([^>]+)>)/ig, "");
range.deleteContents();
range.insertNode(document.createTextNode(rangeToString));
sel.removeAllRanges();
sel.addRange(range);
return;
}
}
if (
range.commonAncestorContainer.parentNode.nodeName == 'H1' ||
range.commonAncestorContainer.parentNode.nodeName == 'H2' ||
range.commonAncestorContainer.parentNode.nodeName == 'H3'
) {
if (range.commonAncestorContainer.parentNode.innerHTML == sel.toString()) {
let parent = range.commonAncestorContainer.parentNode;
parent.remove();
range.deleteContents();
range.insertNode(document.createTextNode(parent.innerHTML));
sel.removeAllRanges();
sel.addRange(range);
}
console.log(range.endOffset);
console.log(sel.toString().length);
if (range.endOffset == range.commonAncestorContainer.parentNode.innerHTML.length) {
let parent = range.commonAncestorContainer.parentNode;
let first = document.createElement("h2");
let second = document.createTextNode(parent.innerHTML.slice(range.startOffset, range.endOffset));
first.appendChild(document.createTextNode(parent.innerHTML.slice(0, range.startOffset)));
newNode = document.createElement("p");
newNode.appendChild(document.createTextNode("New Node Inserted Here"));
parent.remove();
range.insertNode(second);
let secondRange = sel.getRangeAt(0).cloneRange();
sel.removeAllRanges();
sel.addRange(secondRange);
secondRange.insertNode(first);
}
}
else {
range.surroundContents(newTag);
sel.removeAllRanges();
sel.addRange(range);
}
}
}
}
Но возможно, ваш способ более лаконичный, и в духе современного JavaScript.
Спасибо вам большое!