Reputation: 5181
In the official docs about the method Selection.addRange()
I can select the element when I have the specific range, but I don't know how to get the range for a specific word/target which is part of a text
Example:
<p>Hello world</p>
and I want to add the range selection for world
like I would mark it manually with my mouse cursor.
Additionally: How can I select a specific text and mark it based on some Regex rules?
I couldn't find an answer on SO so far.
Official Mozilla docs about addRange()
: https://developer.mozilla.org/en-US/docs/Web/API/Selection/addRange
Upvotes: 1
Views: 143
Reputation: 4516
It works exactly for your example. The function retrieves the Text node from the given Element node, so mind that if the given element contains Element children (rather than direct text content) you have to adjust that function to your need.
const el = document.getElementById('my-text-element');
selectWord(el, 'world');
function selectWord(element, word){
const textNode = element.childNodes[0]; //retrieve the Text node from the Element node
const selection = window.getSelection(); //get the Selection object
const range = document.createRange(); //create the Range object
const text = textNode.textContent; //retrieve the [string] from Text object
const startPosition = text.search(word); //now we look for the word in the [string] value
if(startPosition === -1) return; //if the word does not exist return and do nothing
const endPosition = startPosition + word.length; //we need start and end position to select the found word
range.setStart(textNode, startPosition); //it takes the Text node within we want to select some text, and we pass the starting character
range.setEnd(textNode, endPosition); //we pass the ending character in the same Text node
selection.addRange(range); //pass our prepared Range object and select the text
}
<p id="my-text-element">hello world</p>
Upvotes: 3
Reputation: 1
To select a specific part of an element, that part should have its own tag that you can then select in the javascript
<p>Hello <span id = "xxx">world</span></p>
Upvotes: 0