0

I am trying to wrap every occurrence of the word "example" with <a href="#" class="highlight"></a>. I know I will need to do this via RegExp, and I've had similar versions working. However I also want to check and see if the occurence is already wrapped in an <span>. And if so, to ignore that one.

HTML:

  <span>This</span>
  <span>Example</span>.

  <div> Here is my example text. I will be looking to highlight the word <span class="blue-underline">example.</span> </div>
</body>

JS:

let target = 'example';
var text = document.querySelector('body').textContent;

var regex = new RegExp('(' + target + ')', 'ig');
const newtext = text.replace(regex, '<a href="#" class="highlight">$1</a>');

text.innerHTML = newtext;

Here is my JSFiddle as well.

Is there a way to programmatically accomplish that?

knocked loose
  • 3,142
  • 2
  • 25
  • 46
  • Your code seems to work just fine, I guess there is just 2 mistakes : at the end `text.innerHTML...` -> `document.body.innerHTML...` and at the beginning you should take `...body').innerHTML` instead of `.textContent` to keep the markups https://jsfiddle.net/gui3_/L6pzkxo8/ – gui3 Nov 19 '19 at 18:30
  • @Gui3 good point on the `innerHTML`, however, I am still trying to figure out a way to ignore the replace if there is a `span` around the word "example" – knocked loose Nov 19 '19 at 18:33
  • @WiktorStribiżew Could this be re-opened? Albeit it requests regex, the solution requires XPath and I am working on a solution – MonkeyZeus Nov 19 '19 at 18:42
  • @WiktorStribiżew My answer would involve using something like `var text = document.evaluate("//body//text()[not(ancestor::span) and contains(translate(., 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'example')]", document);`. I'm not sure if that is applicable to the other billion questions. – MonkeyZeus Nov 19 '19 at 18:47
  • 1
    @Wiktor Stribiżew the question you linked to when closing seems to be talking about parsing the whole document into separate span tags. I don't want to parse and modify the entire thing, I essentially need a way to: 1. select all occurrences, 2. check if they are wrapped in an element 3. if not, replace them – knocked loose Nov 19 '19 at 18:49

0 Answers0