I would like to kindly ask you to please take five minutes of your time to help me with the code below. My JS experience is very limited and I have been struggling for hours to get this done, without any success. Any help would be very much appreciated. I am using a JavaScript that highlights certain keywords on the web. For this, the script encloses these keywords within a '<mark>' tag, like this: <mark>highlighted keyword</mark> Code (markup): The function responsible for this job is this... key: "WrRn", value: function WrRn(node, start, end) { var elm = !this.opt.element ? 'mark' : this.opt.element, startNode = node.splitText(start), rtn = startNode.splitText(end - start); var replacement = document.createElement(elm); replacement.textContent = startNode.textContent; startNode.parentNode.replaceChild(replacement, startNode); return rtn; } Code (markup): My question is this: how could I enclose the highlighted keyword in two elements, rather than one? Something like this: <div><mark>highlighted keyword</mark></div> Code (markup): I will later use the 'setAttribute' instruction to apply some CSS styling to the div element. Applying this directly to the 'mark' element would not be helpful, so that's why it's important that I add this second element too. If you could please be highly specific, that would be great. I use this script on a daily basis, and this improvement would make a huge difference for me. Thank you, Alex
Simply create another element, append your existing child (mark) to it, then replaceChild the new element in place of the mark. var rep_outer = document.createElement('div'), rep_inner = rep_outer.appendChild(document.createElement(elm)); rep_inner.textContent = startNode.textContent; startNode.parentNode.replaceChild(rep_outer, startNode); Code (markup): Also don't forget that appendChild / insertBefore / replaceChild all return the element that was inserted. You can leverage that to simplify your code in some places.