Skip to content Skip to sidebar Skip to footer

Change Text Color Of A Part Of Paragraph In Js

I have a JS function to going through a paragraph element. And I have a dictionary. I need to check each word of paragraph with each key of dictionary and if they are matching, I n

Solution 1:

As I commented, you can't color a single word using style, and an array item is not a DOM element and don't have a style property, hence the error Cannot set property 'color' of undefined.

One possible solution would be to replace those words with themselves, wrapped in e.g. a span

In below snippet I simplified your script, as you don't need to iterate all the words in the p, only the object keys and then simply replace the one's found.

Stack snippet

functionn() {
  var a = {
    German: ["German1", "German2"],
    plays: ["plays1", "plays2"],
    forward: ["forward1", "forward2"]
  };
  var p = document.getElementById("p1"),
      keys = Object.keys(a);

  for (j = 0; j < keys.length; j++) {
    p.innerHTML = p.innerHTML.replace( newRegExp("\\b"+keys[j]+"\\b","g"),"<span style='color:red'>" + keys[j] + "</span>")
  }
}
<pid="p1">Marco Reus is a German professional footballer who plays as a forward for Borussia Dortmund and the Germany national team. He is renowned for his versatility, speed and technique, but also for proneness to injury.</p><buttonname="b1"onclick="n()">Next</button>

Post a Comment for "Change Text Color Of A Part Of Paragraph In Js"