Is there an algorithm/library for taking any html document, finding all the 'words' (single words) in the document and the wrapping each word inside a span (or any other html element). I am using angularJS framework which has some jQuery restrictions. Still, even with jQuery i cannot seem to get it to work. I used the .contents().filter().wrap() mechanism outlined on the jQuery documentation. However it is only useful when I want to wrap entire lines of text rather than the individual words. This problem is very frustrating and I would truly appreciate some help. Thanks much!
Okay sorry for the lack of details previously.
My application pulls a string from a database. The string is contains html. I created a custom directive named 'spanner' and bound this directive to the html string on the scope like so:
Inside my directive I try to add a span around each word in the html like so:
.directive('spanner', function($compile){
var linkFn = function(scope, element, attributes)
{
element.append(scope.spanner);
angular.forEach(element.find('*').contents(), function(val, key){
var a = angular.element(val);
var text;
if(a.context.nodeType === 3)
{
text = a.text();
text = text.split(' ');
angular.forEach(text, function(val, key){
if(key%2 === 0){
val = "<span class='even'>" + val + "</span>";
}
else
{
val = "<span ng-class='odd'>" + val + "</span>";
}
text[key] = val;
});
text = text.join(' ');
}
a.html(text);
element.find('*').contents()[key] = a;
});
$compile(element.contents())(scope);
};
return {
scope: {
spanner: '='
},
restrict: 'A',
link: linkFn
};
});
See Question&Answers more detail:os