'Replace multiple strings from CMS in Javascript
This code currently gets 'dynamic words' from the CMS and changes those to span's, which get a eventlistener on it whereas you click on them, something happens. But currently it only gets the last 'dynamic word' from the CMS, instead of all of them. I was thinking about putting it in a loop but I don't think that will work.
Does someone see where the problem is?
CodeSandbox:
https://codesandbox.io/s/musing-wozniak-zzwps2?file=/src/App.js
Solution 1:[1]
Ok I see your CodeSandbox reproduction, you should query the DOM element every loop rather than once above the loop run.
useEffect(() => {
// remove these lines
// const el = document.querySelector(".textblock");
// const text = el.innerHTML;
dynamic_words.map((word) => {
// and replace lines above into the loop
const el = document.querySelector(".textblock");
const text = el.innerHTML;
// ...
})
})
And for the event listeners, you should edit your condition this.innerHTML.includes(dynamic_word)
to this.innerHTML.includes(dynamic_words[i])
Solution 2:[2]
It will be nice if you provide a minimal reproduction that performs your issue(I suggest using CodeSandbox), but I guess the critical part of the issue is const el = document.getElementById('textblock');
and id is not unique, so after your code complete running, functionality works every loop of your dynamic words, but they are overwriting their result on the only one element of id is 'textblock'
, so that you just see the last result only.
nit: code in the ArticleBodyText
will be maintained and read more easily if rewritten completely, it's in a very mutable style right now(query DOM and mutate the innerHTML
directly)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 |