I want to loop through the characters of a text in an element and add spans to the characters. This is pretty easy using jQuery.map():
$elem = $('h1');
var chars = jQuery.map($elem.text().split(''), function(c) {
return '<span>' + c + '</span>';
});
$elem.html(chars.join(''));
The above works great with a simple string, but now I want to change the function so that it also will handle more 'complex' contents like: <h1>T<em>e</em><b>st</b></h1>. Which should be translated to: <h1><span>T</span><em><span>e</span></em><b><span>s</span><span>t</span></b></h1>.
This means I cannot simply loop through all the characters in the element anymore. Is there something I can use to loop through the contents (characters) of an element as well as all children? Or is there another way of achieveing what I want?
Overall idea:
You can recursively iterate over the child nodes. If you encounter an element node, you iterate over its children etc. If you encounter a text node, you are replacing it with a series of span elements.
jQuery
function wrapCharacters(element) {
$(element).contents().each(function() {
if(this.nodeType === 1) {
wrapCharacters(this);
}
else if(this.nodeType === 3) {
$(this).replaceWith($.map(this.nodeValue.split(''), function(c) {
return '<span>' + c + '</span>';
}).join(''));
}
});
}
wrapCharacters($('h1')[0]);
DEMO
JavaScript (without jQuery)
The idea stays the same, and even without jQuery, wrapping each character is not very difficult:
var d_ = document.createDocumentFragment();
for(var i = 0, len = this.nodeValue.length; i < len; i++) {
var span = document.createElement('span');
span.innerHTML = this.nodeValue.charAt(i);
d_.appendChild(span);
}
// document fragments are awesome :)
this.parentNode.replaceChild(d_, this);
Only iterating over the child nodes has to be done carefully because text nodes are getting removed during iteration.
Plain JavaScript example
Try something like (untested):
function recursivelyWrapTextNodes($node) {
$node.contents().each(function() {
var $this = $(this);
if (this.nodeType === 3) { //Node.TEXT_NODE (IE...)
var spans = $.each($this.text().split(""), function(index, element) {
var $span = $("<span></span>");
$span.text(element);
$span.insertBefore($this);
});
$this.remove();
}
else if (this.nodeType === 1) //Node.ELEMENT_NODE
recursivelyWrapTextNodes($this);
}
Example: http://jsfiddle.net/Ymcha/
This is a pure javascript solution
/**
* Enclose every character of a string into a span
* #param text Text whose characters will be spanned
* #returns {string} The "spanned" string
*/
function spanText(text) {
return "<span class='char'>" +
text.split("").join("<\/span><span class='char'>") + "<\/span>";
}
var text = "Every character will be in a span";
document.getElementById("testContent").innerHTML = spanText(text);
document.getElementById("showSpans").textContent = spanText(text);
.char{background-color: grey;}
<! --- Demo for spanning all characters -->
<h3> Spanned text is highlighted grey </h3>
<p id="testContent"> Spanned material here</p>
<h3> This is how the above Highlighted text looks </h3>
<p id="showSpans"></p>
Related
I have a javascript variable like this:
var text = "A <mark id='1'>businessman</mark> should be able to <mark id='1'>manage</mark> his business matters";
I want to wrap each word in a span element with a different id but leave the words which are already wrapped in the <mark> tags. Like this:
text = "<span id='1'>A </span><mark id='1'>businessman</mark><span id='2'>should</span><span id='3'>be </span><span id='4'>able </span><span id='5'>to </span><mark id='2'>manage</mark><span id='6'>his </span><span id='7'>business </span><span id='8'>matters</span>";
I want all this in javascript or jquery but couldn't get it. It would be nice if you people can help me.
Thank you.
Try this,
function removeEmptyStrings(k) {
return k !== '';
}
function getWordsArray(div) {
var rWordBoundary = /[\s\n\t]+/; // split by tab, newline, spaces
var output = [];
for (var i = 0; i < div.childNodes.length; ++i) { // Iterate through all nodes
var node = div.childNodes[i];
if (node.nodeType === Node.TEXT_NODE) { // The child is a text node
var words = node.nodeValue.split(rWordBoundary).filter(removeEmptyStrings); // check for emptyness
for (var j = 0, l = words.length; j < l; j++) {
// adding class txtSpan so that it will not affect your spans already available in your input.
output.push('<span class="txtSpan">' + words[j] + '</span>');
}
} else { // add directly if not a text node
output.push(node.outerHTML);
}
}
return output;
}
var counter = 1,
html = getWordsArray($('#editor')[0]).join('');
$('#output').html(html).find('span.txtSpan').each(function() {
this.id = 'span-' + counter++;
});
span.txtSpan {
padding: 2px;
display: inline-block;
text-decoration: underline;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="editor">
A <mark id='1'>businessman</mark> should be able to <mark id='1'>manage</mark> his business matters
</div>
<div id="output">
</div>
The following quick and dirty method removes the spaces from the <mark id='1'> elements so that the whole string can then be split on spaces, allowing individual words to be wrapped as needed, then it's joined back together, and finally the <mark> elements are restored and renumbered:
var text = "A <mark id='1'>businessman</mark> should be able to <mark id='1'>manage</mark> his business matters";
var spanIndex = 1;
var markIndex = 1;
var result = text.replace(/<mark id='1'>/g,'<mark>')
.split(' ')
.map(function(v){
return v.slice(0,6)==='<mark>' ? v : "<span id='" + spanIndex++ + "'>" + v + '</span>'
})
.join(' ')
.replace(/<mark>/g, function() { return "<mark id='" + markIndex++ + "'>"});
console.log(result);
Note: you said you want to "leave the words which are already wrapped in the <mark> tags", but then your sample output had renumbered the mark element ids (input had both as id='1', but output had 1 and 2). So I've shown code that renumbers, but obviously if you didn't mean to do that you can just make the final .replace() a bit simpler.
I took a much simpler approach that uses the browser's native DOM to parse and transform.
The idea here is to:
create an empty element and don't add it to the document.
take your text you want to transform and wrap and set it as the innerHTML of the temp element.
create an array from the childNodes of the temp element (created when you set the innerHTML)
if the childNode has a nodeValue then it was a text node NOT wrapped in a mark tag. In this case, create a new span element
in the case where the node is already wrapped in an element, just return the element
while you do all of this, remap the IDs to the index they were in from the array. this way they are unique.
Since you're settingthe innerHTML of an element, the DOM will actually fix any mistakes and you get perfect HTML out :)
var text = "A <mark id='1'>businessman</mark> should be able to <mark id='1'>manage</mark> his business matters";
const tempElement = document.createElement('div');
tempElement.innerHTML = text;
let final = Array.from(tempElement.childNodes).map((node, index) => {
if (node.nodeValue) { // if the node is a text node
let newSpanElement = document.createElement('span');
newSpanElement.id = index; // assign an ID
newSpanElement.innerText = node.nodeValue;
return newSpanElement;
}
// else it's inside another element
node.id = index; // reassign the id
return node;
}).map(node => node.outerHTML).join('');
console.log(final);
I'm looking for a way to highlight and format code snippets passed as string for a live style guide. I'm playing around with highlighjs and prettify. They are really helpful and easy for highlighting, but I can't seem to figure out a way to format or whether they can actually do that or not.
By formatting, I mean tabs and newlines to make code legible. I need to pass code as a string to automate the output of dust template I'm using for the style guide.
That is, I want to pass:
"<table><tr><td class="title">Name</td><td class="title">Category</td><td class="title">Results</td></tr></table>"
And get something like:
<table>
<tr>
<td class="title">Name</td>
<td class="title">Category</td>
<td class="title">Results</td>
</tr>
</table>
Any ideas on how to accomplish this?
Thanks!
You could parse this as HTML into a DOM and than traverse every element writing it out and indenting it with every iteration.
This code will do the job. Feel free to use it and surely to improve it. It's version 0.0.0.1.
var htmlString = '<table><tr><td class="title">Name</td><td class="title">Category</td><td class="title">Results</td></tr></table>';
//create a containing element to parse the DOM.
var documentDOM = document.createElement("div");
//append the html to the DOM element.
documentDOM.insertAdjacentHTML('afterbegin', htmlString);
//create a special HTML element, this shows html as normal text.
var documentDOMConsole = document.createElement("xmp");
documentDOMConsole.style.display = "block";
//append the code display block.
document.body.appendChild(documentDOMConsole);
function indentor(multiplier)
{
//indentor handles the indenting. The multiplier adds \t (tab) to the string per multiplication.
var indentor = "";
for (var i = 0; i < multiplier; ++i)
{
indentor += "\t";
}
return indentor;
}
function recursiveWalker(element, indent)
{
//recursiveWalker walks through the called DOM recursively.
var elementLength = element.children.length; //get the length of the children in the parent element.
//iterate over all children.
for (var i = 0; i < elementLength; ++i)
{
var indenting = indentor(indent); //set indenting for this iteration. Starts with 1.
var elements = element.children[i].outerHTML.match(/<[^>]*>/g); //retrieve the various tags in the outerHTML.
var elementTag = elements[0]; //this will be opening tag of this element including all attributes.
var elementEndTag = elements[elements.length-1]; //get the last tag.
//write the opening tag with proper indenting to the console. end with new line \n
documentDOMConsole.innerHTML += indenting + elementTag + "\n";
//get the innerText of the top element, not the childs using the function getElementText
var elementText = getElementText(element.children[i]);
//if the texts length is greater than 0 put the text on the page, else skip.
if (elementText.length > 0)
{
//indent the text one more tab, end with new line.
documentDOMConsole.innerHTML += (indenting + indentor(1) ) + elementText+ "\n";
}
if (element.children[i].children.length > 0)
{
//when the element has children call function recursiveWalker.
recursiveWalker(element.children[i], (indent+1));
}
//if the start tag matches the end tag, write the end tag to the console.
if ("<"+element.children[i].nodeName.toLowerCase()+">" == elementEndTag.replace(/\//, ""))
{
documentDOMConsole.innerHTML += indenting + elementEndTag + "\n";
}
}
}
function getElementText(el)
{
child = el.firstChild,
texts = [];
while (child) {
if (child.nodeType == 3) {
texts.push(child.data);
}
child = child.nextSibling;
}
return texts.join("");
}
recursiveWalker(documentDOM, 1);
http://jsfiddle.net/f2L82m8h/
I have the following code:
<div class="TopMenu">
<h3>Create an Account</h3>
<h3>yup</h3>
<h3>lol</h3>
yo
<ul>
<li sytle="display:">
start or
finish
</li>
</ul>
and I'm using:
$('.TopMenu li:contains("or")').each(function() {
var text = $(this).text();
$(this).text(text.replace('or', 'triple'));
});
It works fine, but suddenly the links aren't active,
how do I fix it?
Thank you very much in advance.
Here's what your jQuery basically translates to when it's being run:
text = this.textContent;
// text = "\n\t\tstart or\n\t\t finish\n\t\t\n";
text = text.replace('or','triple');
// text = "\n\t\tstart triple\n\t\t finish\n\t\t\n";
this.textContent = text;
// essentially, remove everything from `this` and put a single text node there
Okay, that's not a great explanation XD The point is, setting textContent (or, in jQuery, calling .text()), replaces the element's contents with that text.
What you want to do is just affect the text nodes. I'm not aware of how to do this in jQuery, but here's some Vanilla JS:
function recurse(node) {
var nodes = node.childNodes, l = nodes.length, i;
for( i=0; i<l; i++) {
if( nodes[i].nodeType == 1) recurse(node);
else if( nodes[i].nodeType == 3) {
nodes[i].nodeValue = nodes[i].nodeValue.replace(/\bor\b/g,'triple');
}
}
}
recurse(document.querySelector(".TopMenu"));
Note the regex-based replacement will prevent "boring" from becoming "btripleing". Use Vanilla JS and its magic powers or I shall buttbuttinate you!
Change .text() to .html()
$('.TopMenu li:contains("or")').each(function() {
var text = $(this).html();
$(this).html(text.replace('or', 'triple'));
});
See Fiddle
Since or is a text node, you can use .contents() along with .replaceWith() instead:
$('.TopMenu li:contains("or")').each(function () {
var text = $(this).text();
$(this).contents().filter(function () {
return this.nodeType === 3 && $.trim(this.nodeValue).length;
}).replaceWith(' triple ');
});
Fiddle Demo
You need to us .html() instead of .text(),
Like this:
$('.TopMenu li:contains("or")').each(function() {
var text = $(this).html();
$(this).html(text('or', 'triple'));
});
Here is a live example: http://jsfiddle.net/7Mamj/
jsFiddle Demo
You are placing the anchors into text by doing that. You should iterate the matched elements' childNodes and only use replace on their textContent to avoid modifying any html tags or attributes.
$('.TopMenu li:contains("or")').each(function() {
for(var i = 0; i < this.childNodes.length; i++){
if(this.childNodes[i].nodeName != "#text") continue;
this.childNodes[i].textContent = this.childNodes[i].textContent.replace(' or ', ' triple ');
}
});
It is a bit more complicated task. You need to replace text in text nodes (nodeType === 3), which can be done with contents() and each iteration:
$('.TopMenu li:contains("or")').contents().each(function() {
if (this.nodeType === 3) {
this.nodeValue = this.nodeValue.replace('or', 'triple');
}
});
All other approaches will either rewrite the markup in the <li> element (removing all attached events), or just remove the inner elements.
As discussed in the comments below, fool-proof solution will be to use replacement with regular expression, i.e. this.nodeValue.replace(/\bor\b/g, 'triple'), which will match all or as standalone words and not as parts of words.
DEMO: http://jsfiddle.net/48E6M/
i need to highlight all the occurrences of a string in particular div by selecting a string,
once i select a word and click a button it need to highlight all its occurrence inside a div,
eg - if i select
cricket is game
it should highlight all the occurrences of cricket is game some may be like this cricket is game or cricket is game
You can get the browser to do the hard work for you using a TextRange in IE and window.find() in other browsers.
This answer shows how to do it. It will match text that crosses element boundaries and does the highlighting for you using document.execCommand().
Alternatively, James Padolsey recently published a script that I haven't used but looks like it could help: http://james.padolsey.com/javascript/replacing-text-in-the-dom-solved/
mark.js seems pretty good for this. Here's my 3 line fiddle to take an html 'string' and highlight the search string.
$(document).ready(function() {
var html_string = "<b>Major Tom to groundcontrol.</b> Earth is blue <span> and there's something </span> i can do";
var with_highlight = $("<div/>").html(html_string).mark("can");
$("#msg").html(with_highlight);
})
Link to jsfiddle
You can tryout this script Demo
in highlightSearchTerms function of this script var bodyText = document.body.innerHTML; get replace by your divid and than it will do the task for you..
/*
* This is the function that actually highlights a text string by
* adding HTML tags before and after all occurrences of the search
* term. You can pass your own tags if you'd like, or if the
* highlightStartTag or highlightEndTag parameters are omitted or
* are empty strings then the default <font> tags will be used.
*/
function doHighlight(bodyText, searchTerm, highlightStartTag, highlightEndTag)
{
// the highlightStartTag and highlightEndTag parameters are optional
if ((!highlightStartTag) || (!highlightEndTag)) {
highlightStartTag = "<font style='color:blue; background-color:yellow;'>";
highlightEndTag = "</font>";
}
// find all occurences of the search term in the given text,
// and add some "highlight" tags to them (we're not using a
// regular expression search, because we want to filter out
// matches that occur within HTML tags and script blocks, so
// we have to do a little extra validation)
var newText = "";
var i = -1;
var lcSearchTerm = searchTerm.toLowerCase();
var lcBodyText = bodyText.toLowerCase();
while (bodyText.length > 0) {
i = lcBodyText.indexOf(lcSearchTerm, i+1);
if (i < 0) {
newText += bodyText;
bodyText = "";
} else {
// skip anything inside an HTML tag
if (bodyText.lastIndexOf(">", i) >= bodyText.lastIndexOf("<", i)) {
// skip anything inside a <script> block
if (lcBodyText.lastIndexOf("/script>", i) >= lcBodyText.lastIndexOf("<script", i)) {
newText += bodyText.substring(0, i) + highlightStartTag + bodyText.substr(i, searchTerm.length) + highlightEndTag;
bodyText = bodyText.substr(i + searchTerm.length);
lcBodyText = bodyText.toLowerCase();
i = -1;
}
}
}
}
return newText;
}
/*
* This is sort of a wrapper function to the doHighlight function.
* It takes the searchText that you pass, optionally splits it into
* separate words, and transforms the text on the current web page.
* Only the "searchText" parameter is required; all other parameters
* are optional and can be omitted.
*/
function highlightSearchTerms(searchText, treatAsPhrase, warnOnFailure, highlightStartTag, highlightEndTag)
{
// if the treatAsPhrase parameter is true, then we should search for
// the entire phrase that was entered; otherwise, we will split the
// search string so that each word is searched for and highlighted
// individually
if (treatAsPhrase) {
searchArray = [searchText];
} else {
searchArray = searchText.split(" ");
}
if (!document.body || typeof(document.body.innerHTML) == "undefined") {
if (warnOnFailure) {
alert("Sorry, for some reason the text of this page is unavailable. Searching will not work.");
}
return false;
}
var bodyText = document.body.innerHTML;
for (var i = 0; i < searchArray.length; i++) {
bodyText = doHighlight(bodyText, searchArray[i], highlightStartTag, highlightEndTag);
}
document.body.innerHTML = bodyText;
return true;
}
/*
* This displays a dialog box that allows a user to enter their own
* search terms to highlight on the page, and then passes the search
* text or phrase to the highlightSearchTerms function. All parameters
* are optional.
*/
function searchPrompt(defaultText, treatAsPhrase, textColor, bgColor)
{
// This function prompts the user for any words that should
// be highlighted on this web page
if (!defaultText) {
defaultText = "";
}
// we can optionally use our own highlight tag values
if ((!textColor) || (!bgColor)) {
highlightStartTag = "";
highlightEndTag = "";
} else {
highlightStartTag = "<font style='color:" + textColor + "; background-color:" + bgColor + ";'>";
highlightEndTag = "</font>";
}
if (treatAsPhrase) {
promptText = "Please enter the phrase you'd like to search for:";
} else {
promptText = "Please enter the words you'd like to search for, separated by spaces:";
}
searchText = prompt(promptText, defaultText);
if (!searchText) {
alert("No search terms were entered. Exiting function.");
return false;
}
return highlightSearchTerms(searchText, treatAsPhrase, true, highlightStartTag, highlightEndTag);
}
This should get you started: http://jsfiddle.net/wDN5M/
function getSelText() {
var txt = '';
if (window.getSelection) {
txt = window.getSelection();
} else if (document.getSelection) {
txt = document.getSelection();
} else if (document.selection) {
txt = document.selection.createRange().text;
}
document.getElementById('mydiv').innerHTML = document.getElementById('mydiv').innerHTML.split(txt).join('<span class="highlight">' + txt + '</span>');
}
See: Get selected text on the page (not in a textarea) with jQuery
If you want it to work across element boundaries your code will need to be more involved than this. jQuery will make your life easier when doing the necessary DOM traversal and manipulation.
I would use jQuery to iterate over all Elements in your div (Don't know if you have other elements in the div) and then a Regular Expression and do a greedy match to find all occurrences of the selected string in your text(s) in the elements.
First you need to find needed substrings in needed text and wrap them with <span class="search-highlight">. Every time you need to highlight another strings, you just get all the .search-highlight spans and turn their outerHtml into innerHtml.
So the code will be close to:
function highLight(substring, block) {
$(block).find(".search-highlight").each(function () {
$(this).outerHtml($(this).html());
});
// now the block is free from previous highlights
$(block).html($(block).html().replace(/substring/g, '<span class="search-highlight">' + substring + '</span>'));
}
<form id=f1 name="f1" action=""
onSubmit="if(this.t1.value!=null && this.t1.value!='')
findString(this.t1.value);return false"
>
<input type="text" id=t1 name=t1size=20>
<input type="submit" name=b1 value="Find">
</form>
<script>
var TRange=null;
function findString (str) {
if (parseInt(navigator.appVersion)<4) return;
var strFound;
if (window.find) {
// CODE FOR BROWSERS THAT SUPPORT window.find
strFound=self.find(str);
if (!strFound) {
strFound=self.find(str,0,1);
while (self.find(str,0,1)) continue;
}
}
else if (navigator.appName.indexOf("Microsoft")!=-1) {
// EXPLORER-SPECIFIC CODE
if (TRange!=null) {
TRange.collapse(false);
strFound=TRange.findText(str);
if (strFound) TRange.select();
}
if (TRange==null || strFound==0) {
TRange=self.document.body.createTextRange();
strFound=TRange.findText(str);
if (strFound) TRange.select();
}
}
else if (navigator.appName=="Opera") {
alert ("Opera browsers not supported, sorry...")
return;
}
if (!strFound) alert ("String '"+str+"' not found!")
return;
}
</script>
Much better to use rather JavaScript str.replace() function then window.find() to find all occurrences of a filter value. Iterating through the whole page might be bit complicated but if you want to search within a parent div, or within a table str.replace() is just simpler.
In your example you have only one DIV, that is even simpler. Here is what I would do (having your DIV an ID: myDIV):
//Searching for "District Court"
var filter = "District Court";
//Here we create the highlight with html tag: <mark> around filter
var span = '<mark>' + filter + '</mark>';
//take the content of the DIV you want to highlight
var searchInthisDiv = document.getElementById("MyDiv");
var textInDiv = searchInthisDiv.innerHTML;
//needed this var for replace function, do the replace (the highlighting)
var highlighted = textInDiv.replace(filter,span);
textInDiv.innerHTML = highlighted;
The trick is to replace the search string with a span that is having the filter within a tag.
str.replace replaces all occurrences of the search string, so no need to bother with looping. Loop can be used to loop through DIVs or other DOM elements.
I have an HTML-document:
<html>
<body>
<p>
A funny joke:
<ul>
<li>do you know why six is afraid of seven?
<li>because seven ate nine.
</ul>
Oh, so funny!
</p>
</body>
</html>
Now I want to identify the first occurence of "seven" and tag it with
<span id="link1" class="link">
How can this be accomplished?
Do you have to parse the DOM-tree or is it possible to get the whole code within the body-section and then search for the word?
In both cases, after I found the word somewhere, how do you identify it and change it's DOM-parent to span (I guess that's what has to be done) and then add the mentioned attributes?
It's not so much a code I would expect, but what methods or concepts will do the job.
And I am not so much intersted in a framework-solution but in a pure javascript way.
You need to find a DOM node with type TEXT_NODE (3) and containig your expected word. When you need to split a that node into three ones.
First is a TEXT_NODE which contains a text before the word you search, second one is a SPAN node containing the word you search, and third one is another TEXT_NODE containing an original node's tail (all after searched word).
Here is a source code...
<html>
<head>
<style type="text/css">
.link {
color: red;
}
</style>
</head>
<body>
<p>
A funny joke:
<ul>
<li>do you know why six is afraid of seven?
<li>because seven ate nine.
</ul>
Oh, so funny!
</p>
<script type="text/javascript">
function search(where, what) {
var children = where.childNodes;
for(var i = 0, l = children.length; i < l; i++) {
var child = children[i], pos;
if(child.nodeType == 3 && (pos = child.nodeValue.indexOf(what)) != -1) { // a TEXT_NODE
var value = child.nodeValue;
var parent = child.parentNode;
var start = value.substring(0, pos);
var end = value.substring(pos + what.length);
var span = document.createElement('span');
child.nodeValue = start;
span.className = 'link';
span.id = 'link1';
span.innerHTML = what;
parent.appendChild(span);
parent.appendChild(document.createTextNode(end));
return true;
} else
if(search(child, what))
break;
}
return false;
}
search(document.getElementsByTagName('body')[0], 'seven');
</script>
</body>
</html>
This is a function I’ve written a few years ago that searches for specific text, and highlights them (puts the hits in a span with a specific class name).
It walks the DOM tree, examining the text content. Whenever it finds a text node containing the looked-for text, it will replace that text node by three new nodes:
one text node with the text preceding the match,
one (newly created) span element containing the matching text,
and one text node with the text following the match.
This is the function as I have it. It’s part of a larger script file, but it should run independently as well. (I’ve commented out a call to ensureElementVisible which made the element visible, since the script also had folding and expanding capabilities).
It does one (other) thing that you probably won’t need: it turns the search text into a regular expression matching any of the multiple words.
function findText(a_text, a_top) {
// Go through *all* elements below a_top (if a_top is undefined, then use the body)
// and check the textContent or innerText (only if it has textual content!)
var rexPhrase = new RegExp(a_text.replace(/([\\\/\*\?\+\.\[\]\{\}\(\)\|\^\$])/g, '\\$1').replace(/\W+/g, '\\W*')
, 'gi');
var terms = [];
var rexSearchTokens = /[\w]+/g;
var match;
while(match = rexSearchTokens.exec(a_text)) {
terms.push(match[0]);
}
var rexTerm = new RegExp('\\b(' + terms.join('|') + ')', 'gi');
var hits = [];
walkDOMTree(a_top || document.body,
function search(a_element) {
if (a_element.nodeName === '#text') {
if(rexPhrase.test(a_element.nodeValue)) {
// ensureElementVisible(a_element, true);
hits.push(a_element);
}
}
});
// highlight the search terms in the found elements
for(var i = 0; i < hits.length; i++) {
var hit = hits[i];
var parent = hit.parentNode;
if (parent.childNodes.length === 1) {
// Remove the element from the hit list
hits.splice(i, 1);
var text = hit.nodeValue;
parent.removeChild(hit);
var match, prevLastIndex = 0;
while(match = rexTerm.exec(text)) {
parent.appendChild(document.createTextNode(text.substr(prevLastIndex, match.index - prevLastIndex)));
var highlightedTerm = parent.appendChild(document.createElement('SPAN'));
highlightedTerm.className = 'search-hit';
highlightedTerm.appendChild(document.createTextNode(match[0]));
prevLastIndex = match.index + match[0].length;
// Insert the newly added element into the hit list
hits.splice(i, 0, highlightedTerm);
i++;
}
parent.appendChild(document.createTextNode(text.substr(prevLastIndex)));
// Account for the removal of the original hit node
i--;
}
}
return hits;
}
I found the following so question:
Find text string using jQuery?
This appears to be close to what you're trying to do. Now are you attempting to wrap just the text "seven" or are you attempting to wrap the entire content of the <li>?