I am not sure if this is possible or not but I am receiving an element from the backend and I am trying to modify it to convert a word to a link. This is all in Vue3/Typescript.
Example of backend data I can receive:
<p class="random-class">
Foo bar bash is zoo monster <span class="different-class">poop zebra</span>
</p>
Attempt
Let's say that I am trying to convert all words that start with z to an href
const convertWordToHashtag = (element: BackendDataSample) => {
// extracts the text portion of the content to an array of words
const textArray = element.textContent.split(' ');
// checks if anything starts with z
textArray.forEach((word: string) => {
if (word && word.charAt(0) === 'z') {
let newElement = document.createElement('a');
newElement.href = `https://www.google.com/${word}`;
newElement.textContent = word;
// go back to the original element
element.textContent.replace(word, newElement);
}
});
}
My goal is to essentially transform the Element to be used so that it will read:
<p class="random-class">
Foo bar bash is <a href="https://www.google.com/zoo">zoo</a> monster <span class="different-class">poop <a href="https://www.google.com/zebra">zebra</a></span>
</p>
But this doesn't seem to work the replace errors out. Is this the right approach or is there an easier way to do this?
.innerHTMLas necessary.textArray.forEachis missing a closing)createElement. Is there a reason you prefer to manipulate the DOM withcreateElement?