0

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

2 Answers 2

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])

Sign up to request clarification or add additional context in comments.

1 Comment

Oh wow thank you so much man, been stuck with this for days!
1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.