I have a highlighter function that formats the matched words to an anchor with yellow bg-color and I need a function to remove the anchor elements for the next search.
The markup of a matched word, for the first one looks like this:
<a id="searchword1" class="searchword" style="background-color: yellow; text-decoration: none; color: black;">my text</a>
I need to remove the anchor but leave my text there. There are other anchors in my document that I dont want to interfere with. I need to do this in pure Javascript (no jQuery).
- An addational requirement: Don't create new lines after tag removal, leave it as it was.
Thanks to enhzflep, the code until now:
for (z=0;z<szam;z++){
var removal = parent.frames['pagina'].document.getElementById("searchword"+z);
var highlightedText = removal.innerHTML.toLowerCase;
removeh(removal,highlightedText,doc);
}
function removeh(node,high,doc) {
doc = typeof(doc) != 'undefined' ? doc : document;
if (node.hasChildNodes) {
var hi_cn;
for (hi_cn=0;hi_cn<node.childNodes.length;hi_cn++) {
removeh(node.childNodes[hi_cn],high,doc);
}
}
//1. Get element containing text
if (node.nodeType == 3) {
tempnode = node.nodeValue.toLowerCase();
if (tempnode.indexOf(high) != -1) {
nv = node.nodeValue;
nv = node.nodeValue;
ni = tempnode.indexOf(high);
//2. Get the text it contains
before = doc.createTextNode(nv.substr(0,ni));
dochighVal = nv.substr(ni,high.length);
after = doc.createTextNode(nv.substr(ni+high.length));
//3. Get the highlighted element's parent
var daddy = node.parentNode;
//4. Create a text node:
var newNode = document.createTextNode(dochighVal);
//5. Insert it into the document before the link
daddy.insertBefore(before, node);
daddy.insertBefore(newNode, node);
daddy.insertBefore(after, node);
//6. Remove the link element
daddy.removeChild(node);
}
}
}
Where num is the number of matched words.
For some reason this wont work, please help, I will accept the answer that solves this minor problem too.
Two answers had the method right but it is still buggy as it separates the resulting text with new lines. This makes the highlighter function to get the "my word" as separate temporary node values and won't be able to highlight a match for /my.word/.