I have a code element, and I know the text I'm looking for is inside it, for example:
<p>
Lorem ipsum <span class="bold">dolor</span> sit amet
</p>
Note the span that is used for styling specific words.
Now, assume I have a reference to the p element, and I want to programmatically mark the ipsum dolor sit part, how can achieve that?
You can use the
SelectionAPI with aRangeargument to programmatically select text in an element.The
Rangestart and end positions accept a Child Node number, or Character inside aTextnode. In our case, we need to reach theTextnodes to direct to the text position inside them (in our example, it will start on the firstTextnode ofp, in position11, and will end on the lastTextin position4).To find the right node and the text position inside it, use the next function:
This recursive code loops over the child nodes and counts the expected position inside each node.
And now you only need to call this function for your text, create a
Rangeand add it to theSelection: