0

I am trying to select a part of the text similar to selecting it with a mouse.

I referred to this example here: How to select part of a text using select method?.

by using this code I'm able to select all content in the element (by providing the element id). however, I am unable to select only the desired part.

with the following code, I'm able to select all the contents.

var selection = window.getSelection();
var txt = document.getElementsByClassName("xyz");
var range = document.createRange();
range.selectNodeContents(txt);
selection.removeAllRanges();
selection.addRange(range); 

i want to modify the code in such a way that by providing a kewyword and element id I want to slect all the instance of the keyword in that element id.

further, I want to use a loop function to loop through all the instance of the keyword and modify the text. ex: get a substring from the text etc.

leader
  • 31
  • 1
  • 3

1 Answers1

0

If you use getElementsByClassName you get HTMLCollection - all elements with the specified class name. Use loop to go through all this elements. You have possibility to get access to the element text using innerText property.

  • find all elements with class 'post-text' on this page:

let elementsCollection = document.getElementsByClassName("post-text");

  • go through all html elements in the collection and replace the keyword with your own string. Note that the replace() method searches a string for the value (regular expression) and than returns a new string where the values are already replaced. If you want to replase all values in the test use the global (g) modifier.

    let keyWord = 'element';
    let newValue = 'editedElementTest';
    for (i = 0; i < elementsCollection.length; i++) {
         let elementText =  elementsCollection[i].innerText;
         let reg = new RegExp(keyWord, "g");
         let newStringResult = elementText.replace(reg, newValue);
         document.getElementsByClassName("post-text")[i].innerText = newStringResult;
    }
    
Alina_DP
  • 1
  • 2