Skip to content
Advertisement

How to avoid affecting HTML tags in childNodes during innerHTML string.replace()?

I am aiming to replace each word in a document P tags with a span element. While the below code does the trick well for the first case, the following ones overlap, and start to destroy the HTML structure of our P tag completely. See image for unwanted output

Wondering if my approach is a wrong one, or would need some sorcery to only effect the innerHTML between the tags?

JavaScript

Aiming to eventually build a chrome extension that highlights the first 1/2 of the characters of any word on any page. This will help dyslexic people read the web faster. Attaching a link to the whole repo on github for context.

Advertisement

Answer

Okay, so I ended up with replacing the whole TextNode with a new span element instead. This way I can prepare the whole element and append it to its parent. Works perfectly, no regex needed….

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement