I have a html page with text content. On selecting any text and pressing the highlight button, I can change the style of the selected text to highlight the same. To implement this feature, i have written the following method.
sel = window.getSelection(); var range = sel.getRangeAt(0); var span = document.createElement('span'); span.className = "highlight" + color; range.surroundContents(span);
This is working fine if you choose a text with no html tag, but when the text has any html tag in between, it is giving error
Failed to execute ‘surroundContents’ on ‘Range’: The Range has partially selected a non-Text node.
How to solve this problem. Is it possible to highlight the same separately for each part(divided by html tags)?
Advertisement
Answer
if (window.getSelection) { var sel = window.getSelection(); if (!sel) { return; } var range = sel.getRangeAt(0); var start = range.startContainer; var end = range.endContainer; var commonAncestor = range.commonAncestorContainer; var nodes = []; var node; for (node = start.parentNode; node; node = node.parentNode){ var tempStr=node.nodeValue; if(node.nodeValue!=null && tempStr.replace(/^s+|s+$/gm,'')!='') nodes.push(node); if (node == commonAncestor) break; } nodes.reverse(); for (node = start; node; node = getNextNode(node)){ var tempStr=node.nodeValue; if(node.nodeValue!=null && tempStr.replace(/^s+|s+$/gm,'')!='') nodes.push(node); if (node == end) break; } for(var i=0 ; i<nodes.length ; i++){ var sp1 = document.createElement("span"); sp1.setAttribute("class", "highlight"+color ); var sp1_content = document.createTextNode(nodes[i].nodeValue); sp1.appendChild(sp1_content); var parentNode = nodes[i].parentNode; parentNode.replaceChild(sp1, nodes[i]); } }