- User selects a Text then choose color from color-piker
control.
- on click event of the save button from the color-picker, I want to
change the color of the selected text, still keeping the span tag of
italic, bold and a classes but not the textColor classes.
image to show the selection
private _addColor = () => {
const range: any = window.getSelection()!.getRangeAt(0)
const fragment = range.extractContents()
// this.state.textColor is set by color-picker control
const textClassName = getTextClassNames(textStyle(this.state.textColor))
const span = document.createElement('span')
span.className = textClassName.textColor
this._clearNestedColorStyle(fragment)
span.appendChild(fragment)
range.insertNode(span)
}
private _clearNestedColorStyle(node: any) {
node.childNodes.forEach((child: any) => {
if (child.nodeType === 1) {
if (child!.className.substring(0, 'textColor'.length) === 'textColor') {
if (child.hasChildNodes()) {
this._clearNestedColorStyle(child)
this._removeChildNode(child)
} else {
child.innerHTML = child.innerText
}
} else {
if (child.hasChildNodes()) {
this._clearNestedColorStyle(child)
}
}
}
})
}
private _removeChildNode = (node: any) => {
const fragment = document.createDocumentFragment()
while (node.firstChild) {
fragment.appendChild(node.firstChild)
}
node.parentNode.replaceChild(fragment, node)
}
<span>
It is a (selection start) long <span class="textColor-448" >established </span> fact that a
<span class="italic"> reader</span> will be <span class="bold">distracted</span> by the
<a target="_blank" href="#" class="link"> readable</a> <span class="textColor-456" >content of
a page (selection end) when looking </span> at its layout.
</span>