I am working on a html editor and am currently trying to implement rich text functionalities into the program. Right now, I am having difficulties trying to determine the overall position of a node in relation to the commonAncestorContainer.parentElement
of the input, but the way I’ve been doing this is with .indexOf, which works fine if it is the only occurrence of that line in the element, but if there are duplicates it would bold, italic, etc. the wrong element.
Here’s the code that I have been using to get the index of the text, which I then use to concatenate an html string with the changes I need to make that I apply to the parentHTML
node.
const selection = window.getSelection();
const selRange = selection.getRangeAt(0);
const startContainer = selRange.startContainer;
const endContainer = selRange.endContainer;
const startOffset = selRange.startOffset;
const endOffset = selRange.endOffset;
let parentHTML = selRange.commonAncestorContainer.parentElement.innerHTML;
const startIndex = parentHTML.indexOf(startContainer.nodeValue) + startOffset;
const endIndex = parentHTML.indexOf(endContainer.nodeValue) + endOffset;
This is my first time doing something like this, and so I don’t even know if this is the right approach, but I really appreciate any help.
Justin Davis is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.